How to redirect 'print' output to a file?
How can you redirect the output of Python’s print function to a file instead of the console? This guide explains simple methods to capture printed output into a text file for logging or saving results.
Redirecting the output of Python’s print function to a file is a common requirement when you want to save results, logs, or program outputs for later use instead of just displaying them on the console. Python makes this task very simple with the help of the file parameter in print() or by redirecting sys.stdout.
The easiest way is to use the file parameter in print():
with open("output.txt", "w") as f:
print("Hello, world!", file=f)Here, the message "Hello, world!" will be written into output.txt instead of appearing in the terminal.
Another method is to redirect sys.stdout to a file:
import sys
sys.stdout = open("output.txt", "w")
print("This will go into the file")This approach sends all subsequent print() outputs to the file until you reset sys.stdout.
Key points to remember:
- Use with open(...) → It automatically closes the file, ensuring no data is lost.
- File modes matter: "w" overwrites the file, "a" appends to it.
- file parameter is safer than redirecting sys.stdout when you only want specific prints to go to a file.
- Check file location → By default, the file will be created in the current working directory.
By using these methods, you can easily control where your program outputs go, making it easier to log, debug, or store results for future analysis.