Search code examples
pythoninputoutputvalueerror

How to get rid of input/output error for a file created using with statement in python?


process1.py

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

In this code value of c was already defined and text file was also created but it raised this error ValueError: I/O operation on closed file. when I tried to print the text file Main.txt using this code

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

What should I do to make it work?


Solution

  • I think you want:

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

    The code you wrote literally assigns the newly opened file to the variable sys.stdout, executes the wrapped code, and then calls close(sys.stdout). But sys.stdout's value is still the closed file.