Instead of manually opening and closes file objects, use the context
manager that will properly handle opening and closing files for us, even
in the event of some error
Almost entirely fixing print statements, but also a couple importing
changes, wrapped in try/excepts, and one case where dict.keys() not
being a list would be a problem.
Also reverts e41139a397
The real fix for #1907