【问题标题】:What does python with statement do when opening files?python with语句在打开文件时有什么作用?
【发布时间】:2018-04-14 10:38:13
【问题描述】:

我认为

with open('file.txt','r') as f:
    pass

关闭文件 f,但是,我该如何证明呢?我的同事认为,如果文件处于打开状态以进行写入,它将刷新文件。

【问题讨论】:

标签: python file-io with-statement


【解决方案1】:

The documentation clearly states that files will be closed once the with statement is exited.

但是,如果这还不够充分 - 您可以通过以下方式自行检查;

Files 有一个您可以检查的 .closed 属性。

with open("file.txt", "r") as f:
    print(f.closed)  # will print False
print(f.closed)  # will print True

在以非with 方式处理文件时可以使用相同的属性。

f = open("file.txt", "r")
print(f.closed)  # will print False
f.close()
print(f.closed)  # will print True.

这应该足以证明文件确实被关闭了。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 2018-01-27
  • 2011-04-18
  • 1970-01-01
相关资源
最近更新 更多