Search code examples
pythonfile-handling

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:-

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)