f.close()、f.close 和 f.closed 之间的区别

Difference between f.close(), f.close and f.closed

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 是对 file 对象的 close 方法的引用,因此当作为布尔值读取时总是计算为 Truef.close() 是对该方法的调用,它不会 return 任何东西,因此将始终评估为 False,因为 bool(None) 评估为 Falsef.closed 是一个布尔属性,它告诉我们文件是否已关闭。如果您将代码更改为:

if f.closed:
    print('It is closed')
else:
    print('It is open.')

这将 return 您期望的结果。由于您使用了 with ... as f,您的文件将在您离开该语句的范围后自动关闭,因此您不必担心仍然使用 f.close()

f.close 是函数对象,因此使用 if f.close 不会调用该函数。 if f.close 因此总是评估为 True。此外,如果该方法不存在,它不会 return 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'

您可以通过检查 bool(.) 函数 returns:

来检查 if f.close 的计算结果
>>> 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