2

I have this part of code that I originally couldn't get to work:

with open ("Names.txt" , "r+") as f:
    f.seek(0)
    if f.read() == " ":
        print("No text")
    else:
        print("Got text")

It is supposed to check whether the text file has any, well, text.

However, when I would run this code, it would always return "Got text", even if the file was empty.

I found a way to make it work:

with open ("Names.txt" , "r+") as f:
    f.seek(0)
    if not f.read():
        print("No text")
    else:
        print("Got text")

So my question is, why does the second piece of code work while the first doesn't?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Ima Twottle
  • 21
  • 1
  • 1
  • 2

4 Answers4

6

just don't test if a file is empty like this.

What if the file is 5 Terabytes big? it will try to read all the file...

You could try to read 1 byte and see if empty:

if f.read(1):
   # file isn't empty
else:
   # file is empty

or just check the size, no need to open, seek, whatever:

if os.path.getsize(filename):
   # file isn't empty
else:
   # file is empty
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

You are comparing to the string " ". That is not an empty file. The correct code would be something like this:

with open ("Test.txt" , "r+") as f:
     f.seek(0)
     if f.read() == "" :
         print("No text")
     else :
         print ("Got text")
Est
  • 420
  • 3
  • 9
1

Perhaps, because in first case you compare not with an empty string (""), but with a string, which contains single space (" ").

0

In the first case, you're comparing the result against " " (Note the space between the quotation marks). That space is not equal to an empty file, instead it's looking for a file of exactly length 1, where that single character is the space character.

The second code snippet instead is effectively checking if the length of the file is 0, which is what you're actually trying to do (hence why it works)

To fix the first snippet, you'd need to compare against an empty string, f.read() == "". You could also explicitly check the length, len(f.read()) == 0, or not len(f.read()), or you could check the length of the file without reading it.

scnerd
  • 5,836
  • 2
  • 21
  • 36