Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having problem reading a text file in Python

I am trying to read a text file.
But it is not printing anything on the screen

This simple program works fine.

with open("This.txt",'r') as file:
  for line in file:
    print(line)

output:-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Harry Potter,2

Dragon's Nest,1

Happy Life,1

But than I added if else statement in it.
When I run it, I am not getting any output.
My code :-

with open("This.txt",'r') as file:
    if file.read()=='':
        print("File empty")
    else:
        for line in file:
          print(line)

output ->

What could be the problem?

>Solution :

When you call file.read(), Python reads the file till the end. So, after calling the read() function, when Python reaches the else statement, it returns an empty string, since it is at the end of the file. To make Python go back to the start of the file, you need to use file.seek(0). Modified code:

with open("This.txt",'r') as file:
    if file.read()=='':
        print("File empty")
    else:
        file.seek(0) #Add this
        for line in file:
          print(line)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading