How to check whether a file is empty or not
>>> import os
>>> os.stat("file").st_size == 0
True
import os
os.path.getsize(fullpathhere) > 0
Both getsize()
and stat()
will throw an exception if the file does not exist. This function will return True/False without throwing (simpler but less robust):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
If for some reason you already had the file open, you could try this:
>>> with open('New Text Document.txt') as my_file:
... # I already have file open at this point.. now what?
... my_file.seek(0) # Ensure you're at the start of the file..
... first_char = my_file.read(1) # Get the first character
... if not first_char:
... print "file is empty" # The first character is the empty string..
... else:
... my_file.seek(0) # The first character wasn't empty. Return to the start of the file.
... # Use file now
...
file is empty