Rather open the output file here, instead of leaving it open.  Then you can use:

``with open(...) as f:``