How to redirect stdout to a file in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To redirect stdout to a file in Python, you can use the sys module and the stdout attribute, along with the open() function to create a file. Here’s an example:

import sys

# Open a file for writing
with open('output.txt', 'w') as file:
    # Save the current value of stdout
    original_stdout = sys.stdout
    # Redirect stdout to the file
    sys.stdout = file

    # Print to stdout
    print('Hello, world!')

    # Reset stdout to its original value
    sys.stdout = original_stdout

In this example, we create a file named “output.txt” using the open() function. We then save the current value of sys.stdout, which is the standard output stream, to a variable named original_stdout. Next, we set sys.stdout to be the file object we just created. This redirects any subsequent calls to print() to write to the file instead of the console.

We then print “Hello, world!” using print(). This will write to the file instead of the console.

Finally, we reset sys.stdout to its original value. This ensures that any subsequent output will again be written to the console.

Note that this method only works for output that originates from the print() statement or any other calls to sys.stdout. If you want to redirect all output, including output that comes from Python’s built-in input() function, you can use the subprocess module to launch the Python interpreter with a new input/output stream.

Tags:

related content