Python – Print to File

In this article, we shall look at some of the ways to use Python to print to file.

Method 1: Print To File Using Write()

We can directly write to the file using the built-in function write() that we learned in our file handling tutorial.

with open('output.txt', 'a') as f:
    f.write('Hello from AskPython')

Output (Assume that output.txt is a newly created file)

[email protected]:~# python
Hello from AskPython
[email protected]:~# cat output.txt
Hello from AskPython

Method 2: Redirect sys.stdout to the file

Usually, when we use the print function, the output gets displayed to the console.

But, since the standard output stream is also a handler to a file object, we can route the standard output sys.stdout to point to the destination file instead.

The below code is taken from our previous article on stdin, stdout and stderr. This redirects the print() to the file.

import sys
# Save the current stdout so that we can revert sys.stdou after we complete
# our redirection
stdout_fileno = sys.stdout
sample_input = ['Hi', 'Hello from AskPython', 'exit']
# Redirect sys.stdout to the file
sys.stdout = open('output.txt', 'w')
for ip in sample_input:
    # Prints to the redirected stdout (Output.txt)
    sys.stdout.write(ip + '\n')
    # Prints to the actual saved stdout handler
    stdout_fileno.write(ip + '\n')
# Close the file
# Restore sys.stdout to our old saved file handler
sys.stdout = stdout_fileno

Output (Assume that output.txt is a newly created file)

[email protected]:~# python
Hello from AskPython
[email protected]:~# cat output.txt
Hello from AskPython

Method 3: Explicitly print to the file

We can directly specify the file to be printed in the call to print(), by mentioning the file keyword argument.

For example, the below snippet prints to the file output.txt.

print('Hi', file=open('output.txt', 'a'))
print('Hello from AskPython', file=open('output.txt', 'a'))
print('exit', file=open('output.txt', 'a'))

The file now has the three lines appended to it, and we have successfully printed to output.txt!

Using a context manager

However, this method isn’t the best way to resolve this situation, due to the repeated calls to open() on the same file. This wastes time, and we can do better!

The better way would be to explicitly use a context manager with statement, which takes care of automatically closing the file and using the file object directly.

with open("output.txt", "a") as f:
    print('Hi', file=f)
    print('Hello from AskPython', file=f)
    print('exit', file=f)

This gives the same result as before, appending the three lines to output.txt, but is now much faster, since we don’t open the same file again and again.

Method 4: Use the logging module

We can use Python’s logging module to print to the file. This is preferred over Method 2, where explicitly changing the file streams is not be the most optimal solution.

import logging

# Create the file
# and output every level since 'DEBUG' is used
# and remove all headers in the output
# using empty format=''
logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='')

logging.debug('Hi')'Hello from AskPython')

This will, by default, append the three lines to output.txt. We have thus printed to the file using logging, which is one of the recommended ways of printing to a file.