我有一个文本文件,如何检查它是否为空?
>>> import os
>>> os.stat("file").st_size == 0
True
import os
os.path.getsize(fullpathhere) > 0
OSError
并返回 False。 - kennytmls -l
(或在Windows上使用dir
)命令会报告大小为0,同时os.path.getsize()
也会返回0。请注意,这里只是指真正的空文件,而不是仅仅没有文本内容的文件。 - joanisgetsize()
和stat()
都会在文件不存在时抛出异常。这个函数不会抛出异常,返回True/False(更简单但不够健壮):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
os.path.getsize()
。 - David Gayos.path.isfile(fpath)
和os.path.getsize(fpath)
之间,文件可能会被删除,因此存在竞态条件,如果发生这种情况,所提出的函数将引发异常。 - s3rvacTypeError
,因为如果输入的 fpath 是 None
,就会引发此异常。 - Trutane如果你正在使用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
>>> 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
>>> 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
结合 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
由于您没有定义什么是空文件:有些人可能认为只有空白行的文件也是空文件。因此,如果您想检查您的文件是否仅包含空白行(任何空格字符、'\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 ])*
量词——匹配零次或多次,尽可能多地匹配(贪婪模式)$
断言该位置在行尾一个重要的陷阱:使用 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
所以你应该检查要测试的文件是否已被压缩(例如,检查文件名后缀),如果是,则要么退出程序,要么将其解压缩到临时位置,测试未压缩的文件,完成后删除该文件。
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()
read()
读取并检查长度是否为零是不好的做法。 - Or b