Read File Character by Character in Python

Previous
Next

Read file character by character:

  • Read() function return the complete data as object.
  • We can process the data object character by character using for loop.
  • We can easily iterate the file using pre-defined for loop.

Code:

class Process:
    file = None
    def main():
        try:
            Process.file = open("./script.py", "r")
            print("File opened")

            data = Process.file.read()
            for symbol in data:
                print(symbol, end='')

        except FileNotFoundError:
            print("Exception : No such file")

        finally:
            if Process.file != None:
                Process.file.close()
                print("File closed")
        return

Process.main()

Find the length of file:

  • Length of the file is nothing but the number of characters in that file.
  • We can count the characters while iterating the data object using loop.
class Process:
    file = None
    def main():
        try:
            Process.file = open("./script.py", "r")
            print("File opened")

            data = Process.file.read()

            count=0
            for symbol in data:
                count=count+1
            print("File length(Character count) :", count)

        except FileNotFoundError:
            print("Exception : No such file")

        finally:
            if Process.file != None:
                Process.file.close()
                print("File closed")
        return

Process.main()
Previous
Next

Add Comment

Courses Enquiry Form