Fix potential memory leaks

To potentially fix issue #326, I stepped through every usage of open() and made sure to change it to a with open() structure to ensure any opened file is closed.