Fix 'ValueError: I/O operation on closed file.' problems