首页 > 解决方案 > 临时更改 sys.stdout 会给出“ValueError: I/O operation on closed file”

问题描述

来自 StackOverflow 的大家好。我正在做 Marco Buttu 的“Programmare con Python: Guida completa”中的示例。
目的是临时更改 sys.stdout 以逃避将参数传递给 print()

>>> import sys
>>> sys.stdout = open('myfile.log', 'w')
>>> print('escribo en el archivo log...')
>>> print('todavia en el archivo log...')
>>> sys.stdout.close()
>>> open('myfile.log').read()

我收到了这个错误。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.

有人可以向我解释为什么会这样吗?
是否因版本不同而出现错误(书本版本:3.4,实际版本:3.6.5)

我会寻找你的答案。
非常感谢你。

标签: pythonpython-3.xstdoutvalueerror

解决方案


推荐阅读