Python print() to File

Learn different ways to use Python print() function to redirect the print() output of a Python program or script to a file. We will discuss the following methods with their examples and outputs to understand their usage better.

MethodWhen to Use
With open() and print() methodsUseful for basic file output tasks that are NOT limited within a scope
Redirecting sys.stdout temporarilyUseful for redirecting output from third-party libraries or modules that directly print to sys.stdout, and we cannot change their source code
Using redirect_stdout()Useful for redirecting output within a scope / specific context such as a method or unit test
Redirect script output to fileUseful for redirecting all the output of script, including error messages or exceptions

1. Print to File using file Argument

The print() function accepts 5 keyword arguments apart of the objects to print on the standard output (by default, the screen). One such keyword argument is file.

The default value of the file argument is sys.stdout which prints the output on the screen. We can specify any other output target which must be an object with write(string) method.

The given Python program opens the demo.txt in writing mode and write the test 'Hello, Python !' into the file.

sourceFile = open('demo.txt', 'w')
print('Hello, Python!', file = sourceFile)
sourceFile.close()

Program output in a file.

Hello, Python!

2. Redirecting Standard Output Stream to a File

Specifying the file parameter in all print() statements may not be desirable in some situations. We can temporarily redirect all the standard output streams to a file in this case.

Once all the required objects are written in the File, we can redirect the standard output back to the stdout.

import sys

# Saving the reference of the standard output
original_stdout = sys.stdout 	

with open('demo.txt', 'w') as f:
    sys.stdout = f
    print('Hello, Python!')
    print('This message will be written to a file.')
    # Reset the standard output
    sys.stdout = original_stdout 

print('This message will be written to the screen.')

The program outputs to the file after setting the standard output to the file.

Hello, Python!
This message will be written to a file.

The program again outputs to the console after resetting the standard putout target.

This message will be written to the screen.

3. Using redirect_stdout() from contextlib Module

The contextlib module provides redirect_stdout() context manager. This redirects the standard output to a file temporarily.

from contextlib import redirect_stdout

with open('demo.txt', 'w') as file:
    with redirect_stdout(file):
        print("This message will be written to a file.")

print('This message will be written to the screen.')

The output in the file will be:

This message will be written to a file.

And output in the console will be:

This message will be written to the screen.

4. Redirecting Script Output to File

Another way to redirect the output is directly from the command line while executing the Python script. We can use > character to output redirection.

print('Hello, Python!')
$ python3 demo.py > demo.txt

The script output is in the file.

Hello, Python!

Happy Learning !!

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.