python close file descriptor question
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
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
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()
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.
You can also try using os.close(fd) method.