2010-03-24 170 views

回答

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

'stat.ST_SIZE'而不是6 – wRAR 2010-03-24 13:37:11

+1

这也没关系。但我不想导入统计。它的短小和甜蜜,以及返回列表中的大小位置不会很快改变。 – ghostdog74 2010-03-24 13:48:56

+48

@wRAR:os.stat('file')。st_size更好 – 2010-03-24 15:16:50

87
import os  
os.path.getsize(fullpathhere) > 0 
+6

为了安全起见,您可能需要赶'OSError'并返回false。 – kennytm 2010-03-24 13:09:18

+3

使用vs vs.state('file')有什么区别/优点。st_size? – 2017-11-25 00:30:11

+0

看起来像两个是在引擎盖下相同:https://stackoverflow.com/a/18962257/1397061 – 2018-02-07 06:29:59

16

如果由于某种原因,你已经有文件打开,你可以试试这个:

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

两个getsize()stat()将抛出一个异常,如果该文件不存在。这个函数将返回真/假不抛出:

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

绝对像使用''os.path.getsize()'' – 2013-11-19 22:05:35

+3

有一个竞争条件,因为文件可能是在对'os.path.isfile(fpath)'和'os.path.getsize(fpath)'的调用之间移除,在这种情况下,建议的函数会引发异常。 – s3rvac 2017-05-04 09:10:27

+1

更好地尝试和赶上'OSError',而不是像[另一评论]中提出的(http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not/15924160# comment2503155_2507819)。 – j08lue 2017-05-04 13:23:15

6

好了,所以我会结合ghostdog74's answer和意见,只是为了好玩。

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