PyNotes
261 subscribers
125 photos
7 videos
1 file
60 links
**Code is communication**
admin: @Xojarbu
https://t.me/solutions_py for problem solutions
Download Telegram
#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!')
Context Managers
#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