Python print() to File

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

1. Print to file using file keyword 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.

Example: Print to the text file

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)

Program output.

Hello, Python!

2. Redirect the Standard Output Stream to File

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

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.')

Program output.

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

3. Redirect the Python 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.txt

Program output.

Hello, Python!

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.