我有一个文本文件。如何检查它是否为空?
问问题
357164 次
10 回答
446
>>> import os
>>> os.stat("file").st_size == 0
True
于 2010-03-24T13:12:31.733 回答
142
import os
os.path.getsize(fullpathhere) > 0
于 2010-03-24T13:05:41.667 回答
84
如果文件不存在,两者都会抛出getsize()
异常。stat()
此函数将返回 True/False 而不抛出(更简单但不太健壮):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
于 2013-04-10T11:08:00.463 回答
34
如果由于某种原因你已经打开了文件,你可以试试这个:
>>> 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
于 2012-08-10T03:56:17.727 回答
29
如果您使用的是 Python 3,pathlib
则可以使用该方法访问os.stat()
信息,该Path.stat()
方法具有属性st_size
(文件大小以字节为单位):
>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
于 2019-05-02T09:44:42.783 回答
10
结合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
于 2013-04-10T12:45:03.790 回答
9
如果你有文件对象,那么
>>> 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
于 2018-09-10T13:44:20.337 回答
2
由于您尚未定义什么是空文件:有些人可能还会将只有空行的文件视为空文件。所以如果你想检查你的文件是否只包含空行(任何空白字符,'\r','\n','\t'),你可以按照下面的例子:
蟒蛇 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 ])*
量词 - 在零次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)$
在行尾断言位置
于 2020-02-06T03:11:37.143 回答
1
一个重要的问题:使用or函数测试时,压缩的空文件将显示为非零: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
因此,您应该检查要测试的文件是否已压缩(例如检查文件名后缀),如果是,请将其保释或解压缩到临时位置,测试未压缩的文件,然后在完成后将其删除。
于 2019-09-19T00:29:09.583 回答
0
如果要检查 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()
于 2020-01-11T11:22:58.797 回答