Writing to a File with Python’s print() Function
Introduction
Python’s print()
function is typically used to display text either in the command-line or in the interactive interpreter, depending on how the Python program is executed. However, we can change its behavior to write text to a file instead of to the console.
In this article, we’ll examine the many ways we can write to a file with the print()
function.
Redirecting a Python’s Script Output in the Terminal
The quick and dirty way to redirect a Python script’s output is directly from the command-line while executing the script.
For example, if we had a Python file called hello.py
with the following contents:
print("Hallo") # Deliberately in German
We can redirect the output of the file in the shell using a single right angle bracket:
$ python3 hello.py > output.txt
If we open our newly created output.txt
, we’ll see the following contents:
Hallo
However, with this method, all output of the script is written to a file. It is often more flexible to perform this redirection from within the Python script itself.
Redirecting the Standard Output Stream
In Python, the print()
function is more flexible than you might think.