Python print() to File

Learn to use Python print() function to redirect the print output of a Python program or Python script to a file.

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. 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 are closed for this article!

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.