with open('new.txt', 'r+') as f:
print(f.readline())
if f.close:
print('It is closed')
else:
print('It is open.')
如果我运行此代码,输出'It is closed'
. 但是,如果我将 if 语句从 更改f.close
为f.closed()
,我会得到输出'It is open'
。那么我的文件是关闭还是打开?为什么我得到不同的输出?
with open('new.txt', 'r+') as f:
print(f.readline())
if f.close:
print('It is closed')
else:
print('It is open.')
如果我运行此代码,输出'It is closed'
. 但是,如果我将 if 语句从 更改f.close
为f.closed()
,我会得到输出'It is open'
。那么我的文件是关闭还是打开?为什么我得到不同的输出?
f.close
close
是对对象方法的引用file
,因此总是True
在读取为布尔值时进行评估。f.close()
是对该方法的调用,该方法不返回任何内容,因此将始终评估为False
,bool(None)
评估为False
。f.closed
是一个布尔属性,它告诉我们文件是否关闭。如果您将代码更改为:
if f.closed:
print('It is closed')
else:
print('It is open.')
这将返回您期望的结果。如您所用with ... as f
,您的文件将在您离开该语句的范围后自动关闭,因此您不必担心使用f.close()
任何方法。
f.close
是函数对象,因此 usingif f.close
不会调用函数。
if f.close
因此总是评估为 True。此外,如果该方法不存在,它不会返回 False,它会提供语法错误。
>>> type(f.close)
<class 'builtin_function_or_method'>
>>> type(f.doesnotexist)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'doesnotexist'
您可以通过检查函数返回if f.close
的内容来检查评估结果:bool(.)
>>> bool(f.close)
True
从中我们可以看到,这评估为真。
f.closed
是告诉您文件是否已关闭(with
自动关闭)的成员,f.close()
关闭您的文件。
f.closed()
引发 TypeError,因为f.closed
是布尔值,因此不能被调用:
>>> f.closed()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not callable