Is this code
with open(myfile) as f:
data = f.read()
process(data)
equivalent to this one
try:
f = open(myfile)
data = f.read()
process(f)
finally:
f.close()
or the following one?
f = open(myfile)
try:
data = f.read()
process(f)
finally:
f.close()
This article: http://effbot.org/zone/python-with-statement.htm suggests (if I understand it correctly) that the latter is true. However, the former would make more sense to me. If I am wrong, what am I missing?
According to the documentation:
And this is an extended version of your second code snippet. Initialization goes before
try ... finaly
block.It's equivalent to the latter one, because until
open()
successfully returns,f
has no value, and should not be closed.