Redirect standard output to a file in Python
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:
1 2 |
$ python main.py > file. |
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:
1 2 3 4 5 6 |
import sys path = 'path/to/some/dir/file.txt' sys.stdout = open(path, 'w') print('Hello, World') |
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:
1 2 3 4 5 6 7 |
import contextlib path = 'path/to/some/dir/file.txt' with open(path, 'w') as f: with contextlib.redirect_stdout(f): print('Hello, World') |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import sys class Logger: def __init__(self, filename): self.console = sys.stdout self.file = open(filename, 'w') def write(self, message): self.console.write(message) self.file.write(message) def flush(self): self.console.flush() self.file.flush() path = 'path/to/some/dir/file.txt' sys.stdout = Logger(path) print('Hello, World') |
That’s all about redirecting standard output to a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)