Python – Read file line by line

Previous
Next

How can we process the file line by line?

  • For loop can iterate the file line by line by taking file object name directly as an input.
  • read() method is not required to process the data line by line.

Code:

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

            count=0
            for line in Process.file:
                print(line, end='')
                count=count+1
            print("Line count is :", count)

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

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

Process.main()

Closing files:

  • Closing the file will free up the resources which are connected to python application.
  • close() method of file object can release the resource.
file = open("./script.py", "r")
print("file opened")
a = 10/0  # Exception raises – hence file will not be closed…
file.close()
print("file closed")
  • This way of writing code is not recommended.
  • If exception occurs when we perform any operation with the file, the code exits without closing the file.
  • Try….finally block is always recommended to release a resource in any situation.
try:
    file = open("./script.py", "r")
    print("file opened")
finally:
    file.close()
    print("file closed")

with:

  • The best way of closing a file by using ‘with’ statement.
  • We don’t need to call close() method explicitly to release that resource.
with open("script.py" , "r") as file :
    data = file.read()
    print(data)
Previous
Next

Add Comment

Courses Enquiry Form