It is usually said that you should use the with operator when working with files in python, so that regardless of whether the operations on the file are successful, the file will be closed. For instance:
with open('somefile') as f:
instead of something like:
try:
f = open('somefile')
except Exception as e:
print 'error: %s' % e
finally:
f.close()
However, I also heard that Python GC will take care of this anyway, so this is optional.
It's true? If so, why is this template usually offered?
source
share