Reputation:
I think everyone will agree that
with open(file_name, 'mode') as f:
#do things with f
is way better than
f = open(file_name, 'mode')
#do things with f
f.close()
From http://effbot.org/zone/python-with-statement.htm we can read
When the “with” statement is executed, Python evaluates the expression, calls the enter method on the resulting value (which is called a “context guard”), and assigns whatever enter returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s exit method.
In other words, the with
has a similar structure to this
def controlled_execution():
set things up
try:
yield thing
finally:
tear things down
for thing in controlled_execution():
do something with thing
Knowing that :
The try-finally construct guarantees that the "finally" part is always executed, even if the code that does the work doesn’t finish.
So, once the file in open, no matter what happens, it will also be closed, saving from the possibility that the file will stay open without us knowing, returning errors like:
Error: Windows32 | ERROR_SHARING_VIOLATION 32 (0x20) | The process cannot access the file because it is being used by another process.
in case of operations on the same file.
I dont want to digress too much, so I'll go straight to the point, if I have simple code where I know for sure the text file will be closed (EDIT: Thanks to answer now I know that we can't be sure)
f = open(file_name, 'w')
f.write('something')
f.close()
what's the REAL difference with
with open(file_name, 'w') as f:
f.write('something')
In terms of performance and not safety, isn't better the manual opening/closing? The code is definitely shorter to handle, plus there is not indentation. Can someone explain me why even on safe codes people use with open(file)
?
Upvotes: 1
Views: 3861
Reputation: 4445
It's python convention. There's no meaningful performance difference.
Additionally, you don't know for sure that the file will always be closed. The f.write('something')
line can blow up.
Upvotes: 5