提问人:Mark K 提问时间:7/12/2021 最后编辑:halferMark K 更新时间:3/29/2023 访问量:352
ValueError:对关闭的文件执行 I/O 操作(本地计算机正常,但无法 Google Colab)
ValueError : I/O operation on closed file (local machine OK but not Google Colab)
问:
我的文件夹中有一些 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()
答:
1赞
furas
7/12/2021
#1
我运行它,FULL错误消息显示非常刺耳:。
它可以确认问题使 .Colab
sys.stdout.flush()
sys.stdout = outfile
在本地计算机上,您可能运行,因此它总是以 new intepreter 开头,它使用 new 并且不会造成问题,但在(并且可能在其他 Python shell 中)它始终运行相同的解释器,并且当第一次执行关闭时,其他执行可能会有问题使用它。python script
sys.stdout
close
Colab
sys.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) 有效!
评论
with open()
close()
with
close()
with open
sys.stdout = outfile
sys.stdout
outfile
outfile
sys.stdou
sys.stdout.flush()
sys.stdout = outfile