I'm currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.
I didn't start using Python until 2.5 was out, so I'm used to the form:
with open('file.txt', 'r') as f: # do stuff with f
However, there is no with
statement before 2.5, and I'm having trouble finding examples about the proper way to clean up a file object manually.
What's the best practice for disposing of file objects safely when using old versions of python?
A general rule is that a function should not close / reopen a resource it has been given by it's caller, ie this: def foo(fname): with open(fname) a file: bar(file) def bar(file): file. close() with open(file.name, "a") as f2: f2. write("...")
Within the block of code opened by “with”, our file is open, and can be read from freely. However, once Python exits from the “with” block, the file is automatically closed.
Yes they do. This is a CLIB (at least in cpython) and operating system thing. When the script exits, CLIB will flush and close all file objects. Even if it doesn't (e.g., python itself crashes) the operating system closes its resources just like any other process.
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
See docs.python.org:
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
Hence use close()
elegantly with try/finally
:
f = open('file.txt', 'r') try: # do stuff with f finally: f.close()
This ensures that even if # do stuff with f
raises an exception, f
will still be closed properly.
Note that open
should appear outside of the try
. If open
itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open
raises an exception its result is not assigned to f
and it is an error to call f.close()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With