Fix some places in the imager that were relying on cPython's reference semantics to close and flush files that could fail under PyPy.