gho*_*g74 309
>>> import os
>>> os.stat("file").st_size == 0
True
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 111
import os
os.path.getsize(fullpathhere) > 0
Run Code Online (Sandbox Code Playgroud)
ron*_*edg 69
双方getsize()
并stat()
会抛出一个异常,如果该文件不存在.此函数将返回True/False而不抛出:
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
Run Code Online (Sandbox Code Playgroud)
rob*_*ing 25
如果由于某种原因你已经打开文件你可以试试这个:
>>> 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
Run Code Online (Sandbox Code Playgroud)
M.T*_*M.T 18
如果您使用的是 Python 3,则pathlib
可以os.stat()
使用Path.stat()
具有属性st_size
(文件大小以字节为单位)的方法访问信息:
>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
Run Code Online (Sandbox Code Playgroud)
好的,所以我会把ghostdog74的答案和评论结合起来,只是为了好玩.
>>> import os
>>> os.stat('c:/pagefile.sys').st_size==0
False
Run Code Online (Sandbox Code Playgroud)
False
表示非空文件.
那么让我们写一个函数:
import os
def file_is_empty(path):
return os.stat(path).st_size==0
Run Code Online (Sandbox Code Playgroud)
如果你有文件对象,那么
>>> 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
Run Code Online (Sandbox Code Playgroud)