我有一个文本文件。我如何检查它是否为空?


当前回答

>>> import os
>>> os.stat("file").st_size == 0
True

其他回答

import os    
os.path.getsize(fullpathhere) > 0

如果您有文件对象,那么

>>> import os
>>> with open('new_file.txt') as my_file:
...     my_file.seek(0, os.SEEK_END) # go to end of file
...     if my_file.tell(): # if current position is truish (i.e != 0)
...         my_file.seek(0) # rewind the file for later use 
...     else:
...         print "file is empty"
... 
file is empty
>>> import os
>>> os.stat("file").st_size == 0
True

如果出于某种原因,你已经打开了文件,你可以尝试这样做:

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

如果文件不存在,getsize()和stat()都会抛出异常。这个函数将返回True/False而不抛出(更简单但不那么健壮):

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0