【发布时间】:2026-02-20 11:05:01
【问题描述】:
我有一个文本文件。如何检查它是否为空?
【问题讨论】:
标签: python file file-length
我有一个文本文件。如何检查它是否为空?
【问题讨论】:
标签: python file file-length
>>> import os
>>> os.stat("file").st_size == 0
True
【讨论】:
如果您将 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
【讨论】:
如果文件不存在,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.getsize()
os.path.isfile(fpath) 和 os.path.getsize(fpath) 之间可能会删除文件,在这种情况下,建议的函数将引发异常。
OSError,就像建议的in another comment一样。
TypeError,如果输入fpath为None,则会引发。
import os
os.path.getsize(fullpathhere) > 0
【讨论】:
OSError 并返回 False。
ls -l(或 Windows 上的 dir)报告大小为 0,os.path.getsize() 也应该返回 0。
如果你有文件对象,那么
>>> 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
【讨论】:
一个重要的问题:使用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
因此,您应该检查要测试的文件是否已压缩(例如检查文件名后缀),如果是,请将其保释或解压缩到临时位置,测试未压缩的文件,然后在完成后将其删除。
测试压缩文件大小的更好方法:使用the appropriate compression module 直接读取。您只需阅读文件的第一行 for example。
【讨论】:
结合ghostdog74's answer 和 cmets:
>>> 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
【讨论】:
如果由于某种原因你已经打开了文件,你可以试试这个:
>>> 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
【讨论】:
由于您尚未定义什么是空文件:有些人可能还会将只有空行的文件视为空文件。所以如果你想检查你的文件是否只包含空行(任何空白字符,'\r','\n','\t'),你可以按照下面的例子:
Python 3
import re
def whitespace_only(file):
content = open(file, 'r').read()
if re.search(r'^\s*$', content):
return True
说明:上例使用正则表达式(regex)来匹配文件的内容(content)。
特别是:对于 ^\s*$ 的正则表达式,作为一个整体意味着文件是否仅包含空行和/或空格。
^ 在行首断言位置\s 匹配任何空白字符(等于 [\r\n\t\f\v ])* Quantifier — 匹配 0 次到无限次,尽可能多次,按需回馈(贪婪)$ 在行尾断言位置【讨论】:
UnicodeDecodeError。请谨慎使用此解决方案。
如果您想检查 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()
【讨论】:
import json
import os
def append_json_to_file(filename, new_data):
""" If filename does not exist """
data = []
if not os.path.isfile(filename):
data.append(new_data)
with open(filename, 'w') as f:
f.write(json.dumps(data))
else:
""" If filename exists but empty """
if os.stat(filename).st_size == 0:
data = []
with open(filename, 'w') as f:
f.write(json.dumps(data))
""" If filename exists """
with open(filename, 'r+') as f:
file_data = json.load(f)
file_data.append(new_data)
f.seek(0)
json.dump(file_data, f)
filename = './exceptions.json'
append_json_to_file(filename, {
'name': 'LVA',
'age': 22
})
append_json_to_file(filename, {
'name': 'CSD',
'age': 20
})
[{"name": "LVA", "age": 22}, {"name": "CSD", "age": 20}]
【讨论】: