我有一个文本文件。我如何检查它是否为空?
当前回答
如果你正在使用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
其他回答
如果要检查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 os
os.path.getsize(fullpathhere) > 0
>>> import os
>>> os.stat("file").st_size == 0
True
将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}]
如果文件不存在,getsize()和stat()都会抛出异常。这个函数将返回True/False而不抛出(更简单但不那么健壮):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
推荐文章
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何制作好的可复制的熊猫例子
- 2个数字表的余弦相似度
- 如何从熊猫的两列形成元组列
- 如何读一个文本文件到一个列表或数组与Python
- Django可选url参数
- 在matplotlib上为散点图中的每个系列设置不同的颜色
- 如何加载一个tsv文件到熊猫数据框架?
- 从csv文件创建字典?
- 如何在Python中将十六进制字符串转换为字节?
- set()是如何实现的?
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 返回大列表中每n项的python方式
- 如何使用Python中的DLL文件?
- 我如何量化两幅图像之间的差异?