以下语法是否关闭该文件:
lines = [line.strip() for line in open('/somefile/somewhere')]
Run Code Online (Sandbox Code Playgroud)
如果你可以证明它是做什么或不做的话,可以获得奖励积分......
TIA!
Blc*_*ght 23
它应该关闭文件,是的,尽管确实如此,依赖于实现.原因是在列表推导结束后没有对打开文件的引用,因此它将被垃圾收集,并且将关闭文件.
在cpython(python.org的常规解释器版本)中,它会立即发生,因为它的垃圾收集器通过引用计数工作.在另一个插件中,如Jython或Iron Python,可能会有延迟.
如果您想确保文件被关闭,那么使用with语句要好得多:
with open("file.txt") as file:
lines = [line.strip() for line in file]
Run Code Online (Sandbox Code Playgroud)
当with结束时,文件将被关闭.即使在其中引发异常,也是如此.
Joh*_*ooy 13
这就是你应该怎么做的
with open('/somefile/somewhere') as f:
lines = [line.strip() for line in f]
Run Code Online (Sandbox Code Playgroud)
在CPython中,文件应该立即关闭,因为没有对它的引用,但Python语言并不能保证这一点.
在Jython中,在垃圾收集器运行之前,文件不会关闭
小智 5
它不会。可以使用上下文管理器自动关闭它。例如:
with open('/somefile/somewhere') as handle:
lines = [line.strip() for line in handle]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11549 次 |
| 最近记录: |