0
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.closef.closed(),我会得到输出'It is open'。那么我的文件是关闭还是打开?为什么我得到不同的输出?

4

2 回答 2

11

f.closeclose是对对象方法的引用file,因此总是True在读取为布尔值时进行评估。f.close()是对该方法的调用,该方法不返回任何内容,因此将始终评估为Falsebool(None)评估为Falsef.closed是一个布尔属性,它告诉我们文件是否关闭。如果您将代码更改为:

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

这将返回您期望的结果。如您所用with ... as f,您的文件将在您离开该语句的范围后自动关闭,因此您不必担心使用f.close()任何方法。

于 2020-02-03T09:01:09.140 回答
1

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
于 2020-02-03T09:10:46.563 回答