python如何检查文件是否为空
我有一个文本文件。 我怎样才能检查文件是否为空或不空?
>>> import os >>> os.stat("file").st_size == 0 True
import os os.path.getsize(fullpathhere) > 0
如果文件不存在, getsize()
和stat()
将会抛出exception。 此函数将返回True / False而不抛出:
import os def is_non_zero_file(fpath): return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
如果由于某种原因,你已经打开文件,你可以试试这个:
>>> 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
好吧,我会结合ghostdog74的回答和评论,只是为了好玩。
>>> import os >>> os.stat('c:/pagefile.sys').st_size==0 False
False
意味着一个非空文件。
所以我们来写一个函数:
import os def file_is_empty(path): return os.stat(path).st_size==0