Close opened files

There were a few instances where files were opened but not closed. This was generating a ResourceWarning for an unclosed file. Wrapping these in `with` context closes these files automatically and eliminates the warnings.