Solve IOError (closed stream) error