简体   繁体   中英

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? If not, how should it be closed?

It's easy enough to check empirically whether readlines closes the file:

>>> 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 .

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. 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:

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() . (See here for guidance on using with in Python.) But @mypetition's answer is certainly the least painful option.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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