Checking if a text file is blank

Andrew Lee fiacre.patrick at gmail.com
Sun Apr 20 02:54:35 EDT 2008


elnoire 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?


Along with the other posts ... consider using the lstat command to get 
information about the file.


import os
print os.lstat("friends.txt")[6]


gives the size in bytes of friends.txt or throws an OSError if 
friends.txt does not exist.

lstat is portable, it defaults to stat on Windows.



More information about the Python-list mailing list