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
的值仍然是关闭的文件。