This post will discuss how to redirect the standard output to a file in Python.

By default, the standard output is printed to a console. However, you can redirect that output to a file using any of the following functions:

1. Shell redirection

The most common approach to redirect standard output to a file is using shell redirection. The advantage of this approach is that it does not require any code changes. Here’s how you can redirect the stdout and stderr output to a file using the > operator:

Download Code

2. Using sys.stdout

Another simple solution to redirect the standard output to a file is to set sys.stdout to the file object, as shown below:

Download Code

3. Using contextlib.redirect_stdout() function

Another option is using contextlib.redirect_stdout() function in Python 3.4 which sets up a context manager for redirecting sys.stdout to another file. Here’s a working example:

Download Code

4. Custom Logging Class

Finally, you can write your custom logging class to suit your needs. To illustrate, the following class prints the standard output to both console and file:

Download Code

That’s all about redirecting standard output to a file in Python.