我有一个文本文件。我如何检查它是否为空?
当前回答
由于您还没有定义空文件是什么:有些人也可能认为只有空行的文件是空文件。因此,如果你想检查你的文件是否只包含空行(任何空白字符,'\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和无限次之间匹配,尽可能多的次数,根据需要反馈(贪婪) $在一行的末尾断言位置
其他回答
如果出于某种原因,你已经打开了文件,你可以尝试这样做:
>>> 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
如果你正在使用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
>>> import os
>>> os.stat("file").st_size == 0
True
如果文件不存在,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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录