简体   繁体   English

readlines() 是否关闭文件?

[英]Does readlines() close the file?

Is there a need to close a file after doing:执行后是否需要关闭文件:

lines = open(fname).readlines()

Or does readlines() close the file after reading the data?还是readlines()在读取数据后关闭文件? If not, how should it be closed?如果没有,应该如何关闭?

It's easy enough to check empirically whether readlines closes the file:凭经验检查readlines是否关闭文件很容易:

>>> f = open("so.py")
>>> lines = f.readlines()
>>> f.closed
False
>>> f.close()
>>> f.closed
True

A little thought suggests that readlines should not close the file: even with the file "bookmark" at EOF, there are useful commands, starting with seek .一点想法表明readlines应该关闭文件:即使在 EOF 处使用文件“书签”,也有一些有用的命令,从seek开始。

No, the method itself does not close the file automatically.不,该方法本身不会自动关闭文件。 At some point (reliably?) it will be closed if there are no more references to it anywhere in your code, but that is not done by the readlines method.在某些时候(可靠吗?),如果您的代码中没有更多引用它,它将被关闭,但这不是由readlines方法完成的。 You can either do the closing explicitly:您可以明确地关闭:

f = open(...)
lines = f.readlines()
f.close()

Or:或者:

lines = []
with open(...) as f:
    lines = f.readlines()

Or depend on the garbage collector to do it for you, by not maintaining any reference to the file object:或者依靠垃圾收集器为你做这件事,不维护对文件 object 的任何引用:

lines = open(...).readlines()

Which is what you have already, and which will probably be fine in most circumstances.这是您已经拥有的,并且在大多数情况下可能会很好。 I don't know the level of guarantee that the garbage collector gives you there.我不知道垃圾收集器给你的保证水平。

You could use a with statement if you really wanted to, which would close the file without you having to call f.close() .如果你真的想要的话,你可以使用with语句,这将关闭文件而无需调用f.close() (See here for guidance on using with in Python.) But @mypetition's answer is certainly the least painful option. (有关在 Python 中使用with的指导,请参阅此处。)但@mypetition 的答案肯定是最不痛苦的选择。

It doesn't close the file, but you don't have to worry about it, Your file will be closed automatically before it's Garbage collected.它不会关闭文件,但您不必担心,您的文件将在垃圾收集之前自动关闭。

CPython use reference count to clear objects and clearly there is no variable pointing to the object returned by open , so it will be Garbage collected, and python close them before that. CPython 使用引用计数来清除对象,显然没有指向open返回的 object 的变量,因此它将被垃圾收集,并且 python 在此之前关闭它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM