ValueError:对关闭的文件执行 I/O 操作(本地计算机正常,但无法 Google Colab)

ValueError : I/O operation on closed file (local machine OK but not Google Colab)

提问人:Mark K 提问时间:7/12/2021 最后编辑:halferMark K 更新时间:3/29/2023 访问量:352

问:

我的文件夹中有一些 CSV 文件。定义了一个函数,用于读取其中的一列(从每个 CSV 文件中),对值进行乘以,找出最大值,然后打印出来。

我希望将输出写入文本文件。

这些线路在本地机器上运行良好。

但是当它放在 Google Colab 上时,它会产生一个错误,并且似乎不停地运行:

Exception in callback BaseAsyncIOLoop._handle_events(17, 1)
handle: <Handle BaseAsyncIOLoop._handle_events(17, 1)>
Traceback (most recent call last):
  File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py", line 122, in _handle_events
    handler_func(fileobj, events)
  File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 451, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 480, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 434, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 239, in dispatch_shell
    sys.stdout.flush()
ValueError: I/O operation on closed file.

哪里出了问题,如何纠正?

from google.colab import drive
drive.mount('/content/drive')

import pandas as pd
import numpy as np
import glob, sys

folder = "/content/drive/My Drive/Data folder/"

def to_cal(file_name, times):
  df['Result'] = df['Unit Price'] * times
  print (file_name, df['Result'].max())
  return

files = glob.glob(folder + "/*.csv")

with open(folder + 'output (testing).txt', 'a') as outfile:
  sys.stdout = outfile

  for f in files:
    df = pd.read_csv(f)
    file_name = f.replace(folder, "")
    to_cal(file_name, 10)
outfile.close()
python csv io google-colaboratory

评论

0赞 furas 7/12/2021
当你使用时,你不需要,因为应该自动关闭它。你把代码放进错误缩进的唯一想法,现在在里面,它在错误的时刻关闭了文件with open()close()withclose()with open
0赞 furas 7/12/2021
这是完整的 erorr 吗?始终将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图,不是链接到外部门户)作为文本(不是屏幕截图,不是链接到外部门户)。还有其他有用的信息。
0赞 furas 7/12/2021
我不明白你为什么要分配.也许 colab 正在关闭,它也关闭了.或者也许以其他方式:当你关闭然后关闭时,这可能会给 colab 带来问题。sys.stdout = outfilesys.stdoutoutfileoutfilesys.stdou
0赞 furas 7/12/2021
我在 colab 上运行它,FULL 错误消息显示非常刺耳:.它可以确认问题使sys.stdout.flush()sys.stdout = outfile

答:

1赞 furas 7/12/2021 #1

我运行它,FULL错误消息显示非常刺耳:。
它可以确认问题使 .
Colabsys.stdout.flush()sys.stdout = outfile

在本地计算机上,您可能运行,因此它总是以 new intepreter 开头,它使用 new 并且不会造成问题,但在(并且可能在其他 Python shell 中)它始终运行相同的解释器,并且当第一次执行关闭时,其他执行可能会有问题使用它。python scriptsys.stdoutcloseColabsys.stdout

如果要重定向到文件,则最好使用print()

print(..., file=outfile)

或者用正常方式写

text = '{} {}\n'.format(file_name, df['Result'].max())
outfile.write(text)

评论

0赞 Mark K 7/12/2021
谢谢!print(..., file=outfile) 有效!