-2

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

  • 1
    For a stackoverflow question, you need to provide a problem that can be solved. "Here is some working code, but my github doesn't work, why?" Is pretty far from that standard. Pull out the chunk of code that doesn't work, and post that as a question along with expected behavior and observed behavior. – Paul Becotte Feb 16 '21 at 19:33
  • You probably tried to print something *after* closing the file. `sys.stdout.close()` doesn't make `sys.stdout` refer to the "original" standard output again. (You would need something like `sys.stdout = sys.__stdout__` to do that. Reassigning to `sys.stdout` isn't something you typically want to do in the first place.) – chepner Feb 16 '21 at 19:35
  • @PaulBecotte yes I know sorry I'm new here and i just didn't know where the problem is. That's why I wrote if this would help more if someone has time. I already searched the problem for hours and I am using Python now a few months and I don't know much about it so im sorry –  Feb 16 '21 at 19:51

2 Answers2

2

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)
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
-2

Multiple ways to do so

1--

python3 myprogram.py > output.txt

2--

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

3--

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

4--

As @Timur Shtatland suggested you can use a with statement

Luca Sans S
  • 118
  • 8