我有一个文本文件。我如何检查它是否为空?
当前回答
>>> 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
所以你应该检查要测试的文件是否被压缩(例如检查文件名后缀),如果是,要么保释或解压缩到一个临时位置,测试未压缩的文件,然后在完成时删除它。
测试压缩文件大小的更好方法:直接使用适当的压缩模块读取它。例如,您只需要读取文件的第一行。
如果你正在使用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
将JSON追加到文件的完整示例
可重用的功能
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}]
如果您有文件对象,那么
>>> 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
如果要检查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()
推荐文章
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- __FILE__宏显示完整路径
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?