Functions leave file handles open

We are leaking file handles in a few functions, which leads to failing tests on more resource heavy tests and is generally a problem during runtime.