5

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

    def main (self):

        readFile = ReadFile()
        readFile.printData()

    def printData(self):

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

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

            f.close()

        except Exception as ex:
            print(ex)

Now When I run it, I get no output. So I tried debugging it. I see the control jumps from one method to another (main --> printData) and then exists. Its doesn't execute anything within the method. Can you tell me what am I doing wrong here? I am new, so a little insight as to why the code is behaving this way would be nice as well.

hell_storm2004
  • 1,401
  • 2
  • 33
  • 66
  • Your main function should not be within your class definition. Move it to outside the class. It's not clear why you have ReadFile as an object in the first place? It would be simpler to just have a main function calling the printData function. You could pass the filename is as a parameter to printData. – Tom Johnson Nov 13 '18 at 15:00

4 Answers4

18

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()
Silver
  • 1,327
  • 12
  • 24
  • That might very well be true. I am good with Java. So tried to replicate the same in Python. But I guess apples and oranges are not the same. Let me go back to the drawing board. – hell_storm2004 Nov 13 '18 at 15:02
  • I have also edited my answer to include how **I** would do it using a class. See if that makes sense. – Silver Nov 13 '18 at 15:05
1

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)
Nick
  • 3,454
  • 6
  • 33
  • 56
1

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)
HalCat
  • 13
  • 5
Rob Bricheno
  • 4,467
  • 15
  • 29
1

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()
Milo Bem
  • 1,033
  • 8
  • 20