我有一个文本文件。我如何检查它是否为空?
当前回答
如果文件不存在,getsize()和stat()都会抛出异常。这个函数将返回True/False而不抛出(更简单但不那么健壮):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 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
如果你正在使用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
将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}]
结合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
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象