#not_secure
#Secure
f = open('hello.txt', 'w')
f.write('hello, world')
f.close()
This implementation won’t guarantee the file is closed if there’s an exception during the f.write() call#Secure
with open('hello.txt', 'w') as f: f.write('hello, world!')
Context Managers
#not_secure
#Secure
#not_secure
f = open('hello.txt', 'w')
f.write('hello, world')
f.close()
This implementation won’t guarantee the file is closed if there’s an exception during the f.write() call#Secure
with open('hello.txt', 'w') as f:
f.write('hello, world!')
Behind the scenes context manager is implementing the following:f = open('hello.txt', 'w')
try:
f.write('hello, world')
finally:
f.close()
#Source "Python Tricks" by Dan Bader