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 of print
.
For instance, we write:
with open('out.txt', 'w') as f:
print('foo', file=f)
We call open
with the path of the file to write to and 'w'
permission to let us write to the file.
Then we set the file
parameter to f
when we call print
.
Now 'foo'
will be written to out.txt.
The file will be closed automatically when writing is done since we used with
when we open the file.
Conclusion
To redirect print output to a file with Python, we can set the file
argument of print
.