【问题标题】:How to get rid of input/output error for a file created using with statement in python?如何摆脱在 python 中使用 with 语句创建的文件的输入/输出错误?
【发布时间】:2021-12-11 04:07:49
【问题描述】:

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)

我应该怎么做才能让它工作?

【问题讨论】:

    标签: python input output valueerror


    【解决方案1】:

    我想你想要:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 2017-02-15
      相关资源
      最近更新 更多