Use `with` blocks with `open()` instead of manually closing files

`with` blocks automatically close any opened files they receive at the end of the block, so this is a little safer than manually closing files as well as more concise.

(This also shows the commit from the other PR, since it was made on top of that commit.)