【发布时间】:2020-05-19 00:17:12
【问题描述】:
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'。那么我的文件是关闭还是打开?为什么我得到不同的输出?
【问题讨论】:
-
你试过
print(f.close)和print(f.closed())比较吗? -
你正在使用
with open,所以你甚至不应该打电话给.close -
@bereal
print(f.close)给了我<built-in method close of _io.TextIOWrapper object at 0x0000020745364AC8>而另一个显示错误说bool object is not callable
标签: python python-3.x file file-io with-statement