Search code examples
pythonpython-3.xsys

It says "ValueError: I/O operation on closed file" but i opened it


I want to get the console output in a .txt file.

This is what i have:

import sys
print('some text')
a='moretext.1'.split('.')
sys.stdout = open('output.txt', 'w')
print(a)
sys.stdout.close()

here it works but in my program don't. Does someone know what it could be? It says that that its on line 2 or something

And I already searched on Stackoverflow and in the internet but i cant find anything


Solution

  • Do not mess with sys.stdout, instead open the file and print to it like so:

    print('some text')
    a='moretext.1'.split('.')
    with open('output.txt', 'w') as out:
        print(a, file=out)