Menu Close

How to redirect stdout to a file in Python?

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.

Posted in Python, Python Answers