如何检查文件是否为空
- 2025-01-17 09:23:00
- admin 原创
- 95
问题描述:
我有一个文本文件。如何检查它是否为空?
解决方案 1:
>>> import os
>>> os.stat("file").st_size == 0
True
解决方案 2:
import os
os.path.getsize(fullpathhere) > 0
解决方案 3:
getsize()
如果文件不存在,和都会stat()
抛出异常。此函数将返回 True/False - 通常不会抛出:
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
存在竞争条件,因为文件可能会在 os.path.isfile(fpath) 和 os.path.getsize(fpath) 调用之间被删除,在这种情况下,建议的函数仍会引发异常
解决方案 4:
如果您使用的是 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
解决方案 5:
如果由于某种原因您已经打开了该文件,您可以尝试以下操作:
>>> 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
解决方案 6:
如果你有文件对象,那么
>>> 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
解决方案 7:
结合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
解决方案 8:
一个重要的陷阱:使用或函数测试时,压缩的空文件将显示为非零: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
因此,您应该检查要测试的文件是否被压缩(例如检查文件名后缀),如果是,则将其解压缩或保管到临时位置,测试未压缩的文件,然后在完成后将其删除。
测试压缩文件大小的更好方法:使用适当的压缩模块直接读取。例如,你只需要读取文件的第一行。
解决方案 9:
由于您尚未定义什么是空文件:有些人可能还会将只有空白行的文件视为空文件。因此,如果您想检查文件是否仅包含空白行(任何空格字符,'\r','\n','\t'),您可以按照以下示例操作:
Python 3
import re
def whitespace_only(file):
content = open(file, 'r').read()
if re.search(r'^s*$', content):
return True
content
说明:上面的例子使用正则表达式(regex)来匹配文件的内容( )。
具体来说:对于正则表达式:^s*$
作为一个整体意味着如果文件只包含空行和/或空格。
^
断言行首位置s
匹配任何空格字符(等于 [\r\n\t\f\v ])*
量词 - 匹配零次至无限次,尽可能多次,根据需要返回(贪婪)$
断言行尾的位置
解决方案 10:
我最近使用的一个简单方法是:
f = open('test.txt', 'w+')
f.seek(0) #Unecessary but important if file was manipulated before reading
if f.read() == '':
print("no data found")
else:
print("Data present in file")
您可以将上述内容用作您所需用途的灵感(请记住,我对文件处理还很陌生,这似乎适合我在编写的程序中所需的用途)。
解决方案 11:
如果您想检查 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()
解决方案 12:
有一种不使用该os
库的更简单的方法:
with open('filename') as myfile:
if len(myfile.readlines()):
print("It's not empty")