Skip to content Skip to sidebar Skip to footer

Reading A File Line By Line In Python

I am pretty new to Python. So I was trying out my first basic piece of code. So i was trying to read a file and print it line by line in Python. Here is my code: class ReadFile(obj

Solution 1:

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()

Solution 2:

You don't really need a class for this and neither do you need a try block or a file.close when using a context manager (With open ....).

Please read up on how classes are used in python. A function will do for this

def read():

    filename = "C:\\Users\\file.txt"
       with open(filename, 'r') as f:
          for line in f:
             print(line)

Solution 3:

you don't usually put main method in a class. Python is not like Java or C#. all the code outside of class will execute when you load the file.

you only create classes when you want to encapsulate some data with methods together in an object. In your case it looks like you don't need a class at all, but if you want one you have to explicitly create and call it, for example:

class A:
    def __init__(self):
        print('constructor')

    def bang(self):
        print('bang')


# code outside of the class gets executed (like a 'main' method in Java/C#)
a = A()
a.bang()

Solution 4:

There are a few problems here.

The first is that you are declaring a class but then not using it (except from within itself). You would need to create an instance of the class outside of the class (or call a class method on it) in order for it to be instantiated.

class ReadFile:
    def print_data(self):
        ...

# Create a new object which is an instance of the class ReadFile
an_object = ReadFile()
# Call the print_data() method on an_object
an_object.print_data()

Now, you don't actually need to use classes to solve this problem, so you could ignore all this, and just use the code you have inside your printData method:

filename = "H:\\Desktop\\TheFile.txt"

try:
    with open(filename, 'r') as f:
        value = f.readline()
        print(value)

# don't need to do this, as f is only valid within the
# scope of the 'with' block
#    f.close()

except Exception as ex:
    print(ex)

You will find this almost does what you want. You just need to modify it to print the entire file, not just the first line. Here, instead of just reading a single line with f.readline() we can iterate over the result of f.readlines():

filename = "H:\\Desktop\\TheFile.txt"

try:
    with open(filename, 'r') as f:
        for value in f.readlines():  # read all lines
            print(value)

except Exception as ex:
    print(ex)

Post a Comment for "Reading A File Line By Line In Python"