PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

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

 August 16, 2022     input, output, python, valueerror     No comments   

Issue

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.



Answered By - Frank Yellin
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing