by objectified · 11y ago · 0 comments
f = open('foo.txt')
contents = f.read()
f.close()
But I'd prefer this way: with open('foo.txt') as f:
contents = f.read()
Context managers can of course be used for all kinds of things. For more information, see https://docs.python.org/2/library/contextlib.html f = open('foo.txt')
try:
contents = f.read()
finally:
f.close()
So yes, extra reason to prefer the context manager.