How to Save Python Screen Output to a Text File

Capture and redirect Python screen output to text files using built-in methods like stdout redirection or redirect_stdout for cleaner output management.

In Python, you can save your program’s print output (stdout) to a text file using either basic file redirection or more flexible code-based approaches. This is useful when logging output for review or debugging.

Method 1: Redirect Output Using > in Command Line

Run your script and redirect the output
python your_script.py > output.txt
This saves everything that would normally be printed to the terminal into output.txt.This is the simplest way to save output, but only works when running the script from the command line.

Method 2: Use sys.stdout in Code

Import sys and redirect print output
import sys # Redirect stdout to a file sys.stdout = open('output.txt', 'w')   print("This will go to the file instead of the screen")   # Don’t forget to close the file sys.stdout.close()
Useful if you want to control where the output goes from within your script.
Also Read: Best Python Applications And Website Examples in 2025

Method 3: Use Context Manager for Temporary Redirection

Use contextlib.redirect_stdout for safer, limited redirection
import sysfrom contextlib import redirect_stdout   with open('output.txt', 'w') as f:     with redirect_stdout(f):         print("Only this block prints to the file")   print("This will still print to the screen")
Ideal when you want to capture only part of your script’s output to a file.

Tip

Avoid using sys.stdout = ... for long scripts without resetting it, as it will break console output. Use redirect_stdout when possible for safety and clarity.
Related

Python string does not have a built-in .contains() method like some other languages (e.g., Java), but you can easily check if a substring exists using…

10 Oct, 2025

These are the typical reasons why the conda command fails and practical steps to fix them across Windows, macOS and Linux environments. Here are some…

07 Oct, 2025

Hiring Python developers in the USA has become a top priority for companies building complex applications in finance, healthcare, e-commerce and enterprise technology. Companies are…

03 Oct, 2025
Request a Quote Schedule a Meeting