About this question
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.
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.
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Python Expert
Answered on Sep 16, 2025
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:
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.
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common Python interview questions, answered
Guides, tips and career advice on Python from JanBask experts.
Python How to Become a Python Developer: A Step-by-Step Guide for Beginners
Discover how to become a Python Developer via a practical 7-step guide build projects, maintain clean code, practice daily, and…
Python PCEP Certification Guide: Entry-Level Python Programmer Certification
Explore this PCEP certification guide for insights on cost, exam format, passing score, application, training, and study tips.…
Python Top 50+ Python Projects ideas for Beginners to Advanced
Discover innovative Python project ideas, explore advanced Python projects, and find good Python projects for beginners and…
Python How To Comment Out Multiple Lines In Python Like A Pro
Commenting out code is a common practice among programmers. It allows you to temporarily disable parts of your code without…