Reading a File Line by Line in Python [duplicate]

If the idea here is to understand how to read a file line by line then all you need to do is:

with open(filename, 'r') as f:
  for line in f:
    print(line)

It’s not typical to put this in a try-except block.

Coming back to your original code there are several mistakes there which I’m assuming stem from a lack of understanding of how classes are defined/work in python.

The way you’ve written that code suggests you perhaps come from a Java background. I highly recommend doing one of the myriad free and really good online python courses offered on Coursera, or EdX.


Anyways, here’s how I would do it using a class:

class ReadFile:
    def __init__(self, path):
        self.path = path

    def print_data(self):
        with open(self.path, 'r') as f:
            for line in f:
                print(line)

if __name__ == "__main__":
    reader = ReadFile("H:\\Desktop\\TheFile.txt")
    reader.print_data()

Leave a Comment