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


当前回答

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

其他回答

结合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
import os    
os.path.getsize(fullpathhere) > 0

如果你正在使用Python 3的pathlib,你可以使用Path.stat()方法访问os.stat()信息,该方法具有st_size属性(以字节为单位的文件大小):

>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if 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