将使用列表理解来读取文件自动调用 close() [英] will using list comprehension to read a file automagically call close()

查看:28
本文介绍了将使用列表理解来读取文件自动调用 close()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下语法是否关闭文件:

Does the following syntax close the file:

lines = [line.strip() for line in open('/somefile/somewhere')]

如果你能证明它是如何做或不做的,那就加分...

Bonus points if you can demonstrate how it does or does not...

TIA!

推荐答案

它应该关闭文件,是的,尽管它何时关闭取决于实现.原因是list comprehension结束后没有引用打开的文件,所以会被垃圾回收,关闭文件.

It should close the file, yes, though when exactly it does so is implementation dependent. The reason is that there is no reference to the open file after the end of the list comprehension, so it will be garbage collected, and that will close the file.

在 cpython(来自 python.org 的常规解释器版本)中,它会立即发生,因为它的垃圾收集器通过引用计数工作.在另一个交互器中,例如 Jython 或 Iron Python,可能会有延迟.

In cpython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpeter, like Jython or Iron Python, there may be a delay.

如果您想确保您的文件被关闭,最好使用 with 语句:

If you want to be sure your file gets closed, its much better to use a with statement:

with open("file.txt") as file:
    lines = [line.strip() for line in file]

with 结束时,文件将被关闭.即使在其中引发异常也是如此.

When the with ends, the file will be closed. This is true even if an exception is raised inside of it.

这篇关于将使用列表理解来读取文件自动调用 close()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆