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


当前回答

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

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

其他回答

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

一个重要的问题:当使用getsize()或stat()函数测试时,压缩的空文件将显示为非零:

$ python
>>> import os
>>> os.path.getsize('empty-file.txt.gz')
35
>>> os.stat("empty-file.txt.gz").st_size == 0
False

$ gzip -cd empty-file.txt.gz | wc
0 0 0

所以你应该检查要测试的文件是否被压缩(例如检查文件名后缀),如果是,要么保释或解压缩到一个临时位置,测试未压缩的文件,然后在完成时删除它。

测试压缩文件大小的更好方法:直接使用适当的压缩模块读取它。例如,您只需要读取文件的第一行。

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

如果要检查CSV文件是否为空或 不,试试这个:

with open('file.csv', 'a', newline='') as f:
    csv_writer = DictWriter(f, fieldnames = ['user_name', 'user_age', 'user_email', 'user_gender', 'user_type', 'user_check'])
    if os.stat('file.csv').st_size > 0:
        pass
    else:
        csv_writer.writeheader()

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