如何消除python中使用with语句创建的文件的输入/输出错误



process1.py

import sys
with open("Main.txt", "w+") as sys.stdout:
eval(c)

在这个代码中,已经定义了c的值,也创建了文本文件,但当我试图使用这个代码打印文本文件Main.txt时,它引发了这个错误ValueError: I/O operation on closed file.

import process1
f = open("Main.txt", "r")
for x in f:
print(x)

我该怎么做才能让它发挥作用?

我想你想要:

with open("Main.txt", "w+") as file:
with contextlib.redirect_stdout(file):
...

您编写的代码将新打开的文件实际分配给变量sys.stdout,执行封装的代码,然后调用close(sys.stdout)。但sys.stdout的值仍然是关闭的文件。

最新更新