. Advertisement .
..3..
. Advertisement .
..4..
Redirecting print output to a file in Python is not challenging as there are various methods you can employ. This article introduces the most useful and straightforward ways to accomplish this task for both coding beginners and experienced ones.
How To Redirect Print Output To A File In Python
All standard outputs are by default printed to a console. Yet, they can also be redirected to a specific files with the following functions:
Method 1: Use The write() Function
The write()
function is built-in in Python, which is designed to write or add a text into a file. There are two operations in this function to do these tasks.
The w mainly aids the writing process by emptying the file beforehands. On the other hand, the a operator allows coders to add texts to the existing one in the file.
To apply this write()
function, you should use the open()
one first to open the file.
Example:
with open("randomfile.txt", "a") as o:
o.write('Hello')
o.write('This text will be added to the file')
Method 2: Use The print() Function
Like the first method, you also need to use the open()
function to execute the desired file. The print()
function enables you to choose between the w and a operators.
After applying it to redirect the output to a file, let’s use the close()
function to close the file. Yet, note that this action will make the file unable to read and change. If you make changes in the file after applying the close()
, there will surely be an error.
with open("randomfile.txt", "w") as external_file:
add_text = "This text will be added to the file"
print(add_text, file=external_file)
external_file.close()
Overall, there are five keyword arguments accepted in this function, besides the ones on the standard output.
Method 3: Use sys.stdout
The built-in sys module is often used to deal with the Python runtime environment. You need to import it first to use the sys.stdout
.
The sys.stdout is practical in displaying the output to the screen’s main console. Its form is variable, including an input prompt, an expression, and a statement.
Before using this option, you should define a file’s path clearly. Without it, the file will not perform any operations.
import sys
file_path = 'randomfile.txt'
sys.stdout = open(file_path, "w")
print("This text will be added to the file")
Method 4: Use The contextlib.redirect_stdout() Function
It would be best to use the contextlib module with the with statement. In this case, the contextlib.redirect_stdout()
will set up a context manager to redirect the sys.stdout to files temporarily.
import contextlib
file_path = 'randomfile.txt'
with open(file_path, "w") as o:
with contextlib.redirect_stdout(o):
print("This text will be added to the file")
Conclusion
A standard output, including the print one, can be printed to a Python file. The post discusses four main methods to accomplish the task. So check again to find a suitable one.
Leave a comment