Added better unicode handling in the operations that write out files.

Also updated all file interaction to use file() instead of the deprecated open().
Replaced the file operations with context managers.