Categories
Python Answers

How to redirect print output to a file with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *