Make sure file handles are closed in case exceptions occur

This commit ensures we always call `f.close()` on each of the file handles in `files`. Each opened file handle should be closed and this commit ensures that happens, even when exceptions occur.