contextlib.redirect_stdout

The contextlib.redirect_stdout function in Python temporarily redirects the output of print() and other writing operations. It's useful when you need to write output to a file or capture it for further processing.

from contextlib import redirect_stdout

with open('output.txt', 'w') as f:
    with redirect_stdout(f):
        print("This will be written to file")  

# "This will be written to file" will be saved in output.txt

Comments (0)

Leave a comment