I have a text file. How can I check whether the file is empty or not empty?
>>> import os >>> os.stat("file").st_size == 0 True
import os os.path.getsize(fullpathhere) > 0
stat() will throw an exception if the file does not exist. This function will return True/False without throwing:
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" #first character is the empty string.. ... else: ... my_file.seek(0) #first character wasn't empty, return to start of file. ... #use file now ... file is empty
Ok so I’ll combine ghostdog74’s answer and the comments, just for fun.
>>> import os >>> os.stat('c:/pagefile.sys').st_size==0 False
False means a non-empty file.
So let’s write a function:
import os def file_is_empty(path): return os.stat(path).st_size==0