I think this question is more of a “coding style” rather than technical issue.
Said I have a line of code:
buf = open('test.txt','r').readlines()
...
Will the file descriptor automatically close, or will it stay in the memory?
If the file descriptor is not closed, what is the prefer way to close it?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you assign the file object to a variable, you can explicitly close it using .close()
f = open('test.txt','r')
buf = f.readlines()
f.close()
Alternatively (and more generally preferred), you can use the with keyword (Python 2.5 and greater) as mentioned in the Python docs:
It is good practice to use the
with
keyword when dealing with file
objects. This has the advantage that
the file is properly closed after its
suite finishes, even if an exception
is raised on the way. It is also much
shorter than writing equivalent
try-finally blocks:
>>> with open('test.txt','r') as f:
... buf = f.readlines()
>>> f.closed
True
Method 2
Usually in CPython, the file is closed right away when the reference count drops to zero (although this behaviour is not guaranteed for future versions of CPython)
In other implementations, such as Jython, the file won’t be closed until it is garbarge collected, which can be a long time later.
It’s poor style to have code that works differently depending on the implementation’s behaviour.
If it’s just for a quickie script or something you are trying in the interpreter shell it’s good enough, but for any sort of production work you should usually use a context manager as in Falmarri’s answer
Method 3
It will stay in memory until the garbage collector closes it. You should always explicitly close your file descriptors. Just do something like this:
with open('test.txt', 'r') as f:
buf = f.readlines()
Method 4
It will be automatically closed, but it depends on implementation exactly when. It’s nicer to explicitly use a with-block, but if you are just writing a small script for yourself that you run occasionally it doesn’t really matter.
Method 5
You can also try using os.close(fd) method.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0