Using the with syntax is convenient because you can omit close (), which you forget about, and it also improves readability.
python
#with statement used
with open("text.txt", 'w') as text:
text.write("Hello, world!")
If you try to write this without the with statement, it will be as follows.
python
#with statement not used
text = None
try:
text = open("text.txt", 'w')
try:
text.write("Hello, world!")
except:
raise
finally:
if text:
text.close()
Recommended Posts