I often do not close the file after reading it
for line in open(FileName):
# do something
I also reopen the file again in the same program.
for line in open(FileName):
# do something else
My question is whether there are any drawbacks in this approach?
I have seen posts that claim that file should be open with with
with open(FileName) as fp:
But what is the advantage of this approach?
In some situations, you might get away with not closing the file without experiencing adverse effects. CPython (the most popular Python implementation) will close the file immediately after the loop when using
for line in open("filename"):, provided no further references to the file exist. In other Python implementations, closing the file may be delayed, but it will eventually be closed.There are a few issues, though:
Sometimes hidden references to a file continue to exists. If an exception is thrown in a function, the traceback associated with the exception contains a reference to the execution fram of the function, so all local variables continue to exist – this may keep files open for longer than expected even in CPython.
You may run out of file descriptors when opening many files, since you don’t have control over the time they get closed again.
Python 3.2 or above will raise a
ResourceWarningfor every file that was not closed (this warning can be disabled, but anyway).In summary, it’s simply not worth the trouble. Always use
with, and forget about these issues. There is enough to keep in mind while prgramming anyway.