Python Tip #26 (of 365):

When opening a file, use a "with" block... especially for writing!

Using a "with" block to open a file will close it automatically when the "with" block exits: pym.dev/creating-and-writing-f

So this:

with open("example.txt", mode="wt") as file:
file.write("An example file\n")

Is pretty much the same as this:

file = open("example.txt", mode="wt")
try:
file.write("An example file\n")
finally:
file.close()

๐Ÿงต(1/4)

0

If you have a fediverse account, you can quote this note from your own instance. Search https://mastodon.social/users/treyhunner/statuses/115963019979741312 on your instance and quote it. (Note that quoting is not supported in Mastodon.)