Is python with a statement really necessary to ensure file closure?

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:
    # do stuff to file

instead of something like:

try:
    f = open('somefile')
    # do stuff to file
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?

+4
source share

All Articles