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.

Also Read:

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.