Sometimes, we want to redirect ‘print’ output to a file with Python.
In this article, we’ll look at how to redirect ‘print’ output to a file with Python.
How to redirect ‘print’ output to a file with Python?
To redirect ‘print’ output to a file with Python, we can set the file
argument when we call print
.
For instance, we write
with open('out.txt', 'w') as f:
print('Filename:', filename, file=f)
to open the out.txt file with open
.
Then we call print
to set the file
argument to the opened file f
to save the print
output to out.txt.
Conclusion
To redirect ‘print’ output to a file with Python, we can set the file
argument when we call print
.