Home > Software design >  How to export Python printed output to txt file at the end of code
How to export Python printed output to txt file at the end of code

Time:11-05

I have several thousand lines of code that all ultimately results in a few strings being printed using print() functions. Is there a way to, at the bottom of my code, export everything that has been printed to a txt file?

CodePudding user response:

This will help.

python main.py > output.txt

The operator > redirects the output of main.py from stdout to the regular file output.txt.

CodePudding user response:

You can do this with redirection in your shell or reopening sys.stdout. Here are both ways:

  1. Reopen sys.stdout:

At the beginning of your code, you can use this code:

import sys

sys.stdout = open('logfile', 'w')

# ... rest of your program ...

and everything printed to standard output (including print() calls) will be written to logfile. This method will always work.

  1. Redirection in your shell:

This is my preferred method if you're running the script from the command line every time. In some niche cases, this won't work (ie: the script is being run by some other program), but it will work for 90% of cases. You can simply run your original script like this:

python myFile.py > logfile

and everything will be written to logfile. If for some reason this doesn't work for you, use method #1.

  • Related