Categories
Python Answers

How to redirect stdout to a file in Python?

Spread the love

Sometimes, we want to redirect stdout to a file in Python.

In this article, we’ll look at how to redirect stdout to a file in Python.

How to redirect stdout to a file in Python?

To redirect stdout to a file in Python, we can set sys.stdout to a file.

Then when we want to send stdout to the screen again, we call sys.stdout.close.

For instance, we write:

import sys
sys.stdout = open('file', 'w')
print('test')
sys.stdout.close()

We set sys.stdout to a file with path file.

We open file with write permission.

And then we call print to print some text, which will be written to file.

Finally, we call sys.stdout.close to close the file.

Conclusion

To redirect stdout to a file in Python, we can set sys.stdout to a file.

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 *