Reputation: 781
Is it me or to open or close a file in python uses different methods making it really not intuitive? Is there a better way to do it?
example:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
Now, why I use the built-in "function" open but to close the file I don't have function "close" but I have to call the "object" method "close".
Upvotes: 1
Views: 221
Reputation: 12243
Use the with
keyword to make it a bit more intuitive. It will automatically close the file when you dedent. From the docs:
The ‘with‘ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed.
...
After this statement has executed, the file object in f will have been automatically closed, even if the for loop raised an exception part- way through the block.
An example:
with open('file.txt', 'r') as f:
# do stuff with f
# Do some other stuff - we dropped down a level of indentation, so the file is closed
More specifically, it will initially call the context's __enter__
method - this does the initial file opening. Whatever is returned by __enter__
is set using the as
statement - in this case, the file returns self
and it will be set to f
. When the with
block is done, it will call the context's __exit__
method. For a file context, this does the normal finally
block handling of closing the file.
Note that the with
block won't handle exceptions for you, it just ensures __exit__
is called (and that will gracefully closed the file) even if they do happen . So if you have a ValueError
while working with the file you'll still need a try...catch
block inside the with
block to handle whatever that may do to your calculations/script/etc.
As Marcin noted, most languages do this in a try...catch...finally
block. Java, for example, does this:
BufferedReader reader = null;
try {
reader = new BufferedReader(new File("file.txt"));
// Read in data and do stuff
} catch (Exception e) {
// Shouldn't be this generic, but you get the idea
e.printStackTrace();
} finally {
// Always executes
if (reader != null) reader.close();
}
Upvotes: 6