我有一个文本文件。我如何检查它是否为空?
当前回答
如果出于某种原因,你已经打开了文件,你可以尝试这样做:
>>> 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
其他回答
import os
os.path.getsize(fullpathhere) > 0
一个重要的问题:当使用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
所以你应该检查要测试的文件是否被压缩(例如检查文件名后缀),如果是,要么保释或解压缩到一个临时位置,测试未压缩的文件,然后在完成时删除它。
测试压缩文件大小的更好方法:直接使用适当的压缩模块读取它。例如,您只需要读取文件的第一行。
>>> import os
>>> os.stat("file").st_size == 0
True
如果出于某种原因,你已经打开了文件,你可以尝试这样做:
>>> 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]) *量词-在0和无限次之间匹配,尽可能多的次数,根据需要反馈(贪婪) $在一行的末尾断言位置
推荐文章
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何制作好的可复制的熊猫例子
- 2个数字表的余弦相似度
- 如何从熊猫的两列形成元组列
- 如何读一个文本文件到一个列表或数组与Python
- Django可选url参数
- 在matplotlib上为散点图中的每个系列设置不同的颜色
- 如何加载一个tsv文件到熊猫数据框架?
- 从csv文件创建字典?
- 如何在Python中将十六进制字符串转换为字节?
- set()是如何实现的?
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 返回大列表中每n项的python方式
- 如何使用Python中的DLL文件?
- 我如何量化两幅图像之间的差异?