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.
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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With