Use "with open"

In case of an error (example: disk full) Files currently aren't closed and handles aren't released. 

So now use "with open" to make sure that they are closed and handles released in any case.