Checking if a text file is blank

Dan Bishop danb_83 at yahoo.com
Sun Apr 20 02:25:33 EDT 2008


On Apr 20, 1:04 am, elno... at gmail.com wrote:
> Greetings!
>
> I've just started learning python, so this is probably one of those
> obvious questions newbies ask.
>
> Is there any way in python to check if a text file is blank?
>
> What I've tried to do so far is:
>
>                 f = file("friends.txt", "w")
>                 if f.read() is True:
>                         """do stuff"""
>                 else:
>                         """do other stuff"""
>                 f.close()
>
> What I *mean* to do in the second line is to check if the text file is
> not-blank. But apparently that's not the way to do it.
>
> Could someone set me straight please?

The flaw in your code is that "f.read() is True" doesn't do what you
think it does.

(1) The "is" operator is a test for object IDENTITY.  Two objects can
be equal but distinct

>>> list1 = list2 = [1, 2, 3]
>>> list1 is list2
True
>>> list1[-1] = 4
>>> list2
[1, 2, 4]

>>> list1 = [1, 2, 3]
>>> list2 = [1, 2, 3]
>>> list1 is list2
False
>>> list1[-1] = 4
>>> list2
[1, 2, 3]

(2) Even if you used "f.read() == True", it still wouldn't work in
Python.  Values can be true or false (in the context of an if or while
statement) without being equal to True or False.

Values that are equal to True:
True, 1, 1.0, (1+0j), decimal.Decimal(1)

Values that are true but not equal to True:
"spam", "1", (1,), [1], set([1]), {1: 2}, etc.

Values that are equal to False:
False, 0, 0.0, 0j, decimal.Decimal(0)

Values that are false but not equal to False:
"", (), [], set()

And even if you are sure that you're only dealing with values of 0 or
1, it's unnecessary to write "if x == True:".  It's redundant, just
like "if (x == True) == True:" or "if ((x == True) == True) ==
True:".  Just write "if x:".  Or, in this specific case, "if
f.read():".

(3) While not affecting your program's correctness, it's rather
inefficient to read a gigabytes-long file into memory just to check
whether it's empty.  Read just the first line or the first character.
Or use os.stat .



More information about the Python-list mailing list