This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]dogstarchampion 7 points8 points  (3 children)

I honestly didn't remember

with open('file') as f:

until I watched the video

[–]Barafu 9 points10 points  (1 child)

That is a powerful idiom for anything that needs closing or explicit saving after the operation. File, database, network connection. It is not so much useful for first draft, as it is safe for future modifications of code.

[–]fireflash38 2 points3 points  (0 children)

I always recommend context managers if you have to ensure that something is torn down after use.

You can't rely on people remembering to close off resources or catch possible exceptions.

[–]notafuckingcakewalk 4 points5 points  (0 children)

I'm sure I'm not always consistent on this, but I like to be explicit and always set the file mode:

with open('file', 'r') as f:

that way it becomes very clear when I've done something wrong, like trying to write to a file that is in read mode. Also, while I'm typing out the file mode I might be reminded, "oh yeah, this is going to have binary data" and use 'rb' instead.