Extract constants & use 'with' syntax for file writing

One main advantage of writing files using 'with' is that in the event that file writing fails for any reason the file writing is automatically closed. It's also a bit neater. 

This means that where the script pointed to the open file, it now stores the filename - a bit different but functions the same.

Comments, suggestions etc welcome!

best - J.