How to Write Print Output to a File in Python
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. It was not hard-coded in such a way that specified text can only be written to the display. Instead, it sends text to a location called the standard output stream, also known as stdout
.
All UNIX systems have three main pipes - standard input pipe (stdin
), standard output pipe (stdout
) and standard error pipe (stderr
).
By default, the standard output pipe points to the interactive window used to execute the program, so we normally see text printed out on the screen. However, the standard output can be redirected to other locations, such as files, for convenience.
If the standard output is redirected to a specific file, the text specified in the print()
function will be written to that file instead of being displayed on the screen.
In Python, a reference to the standard output can be obtained using the stdout
object of the sys
module. It is a file-like object, meaning it has methods that allow Python to read and write from it like an actual file.
Let's see an example where we change stdout
to be a file:
import sys print('This message will be displayed on the screen.') original_stdout = sys.stdout # Save a reference to the original standard output with open('filename.txt', 'w') as f: sys.stdout = f # Change the standard output to the file we created. print('This message will be written to a file.') sys.stdout = original_stdout # Reset the standard output to its original value
The print()
function takes the supplied string argument, appends a newline character to the end, and calls the stdout.write()
method to write it to standard output.
In the example above, we first print a line of text as we're accustomed to, which will be displayed in the console when we run the file. We then reassigned stdout
to our custom file object - f
. Since a file object has a perfectly valid write()
method, our printed value gets written to the file without a problem.
Note that it is good practice to store the original value of the standard output in a variable before changing it. This way we can reset the standard output to its original value after we're done, which can help avoid confusion.
Let's save the code to a new file, printToFile.py
. And then, let's execute it:
$ python3 printToFile.py
We'll see the following output in the Terminal:
This message will be displayed on the screen.
And the script will create a new file called filename.txt
with the following contents:
This message will be written to a file.
You successfully redirected data from the standard output stream to a file. Let's see how we can do this to another popular file-like object that's dedicated to programming errors.
Redirecting the Standard Error Stream
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
In Python, errors are written to the standard error stream, also known as stderr
. This also defaults to the interactive window but can be changed via the sys.stderr
object. If we wanted to print values to the stderr
, we could simply redirect the sys.stdout
to point to the sys.stderr
.
Create a file called printToStderr.py
and add the following code:
import sys print('This message will be displayed via standard output.') original_stdout = sys.stdout # Save a reference to the original standard output sys.stdout = sys.stderr # Redirect the standard output to the standard error. print('This message will be displayed via the standard error.') sys.stdout = original_stdout # Reset the standard output to its original value
This example is almost identical to the previous one, except that instead of redirecting the standard output stream to a file, we redirect it to the standard error stream. If the standard error stream was also redirected somewhere else, the output would be sent to that location instead of to the screen.
Let's run this file:
$ python3 printToStderr.py
Our output would show:
This message will be displayed via standard output. This message will be displayed via the standard error.
While it may appear like regular output to us, for the computer it is displayed through different pipelines.
Print Using the "file" Parameter
In the previous examples, we explicitly redirected the standard output to another file-like object by changing the stdout
object. However, for convenience we can do this directly from within the print()
function by specifying the output location with the file
parameter:
For example, if we wanted to print directly to a file without changing the entire script's stdout
, we would write:
import sys print('This message will be displayed on the screen.') with open('filename.txt', 'w') as f: print('This message will be written to a file.', file=f)
As we did not fiddle with redirecting the standard output explicitly, we no longer have to reset it to its initial value. As a result, this is the preferred way to write to a file with the print()
function.
Note: Although the parameter's name is file
, remember that it works with any file-like object. If you wanted to print to stderr
, for example, you would change the print()
statement to:
print('This message will be written to stderr.', file=sys.stderr)
Conclusion
In this article, we discussed redirecting Python's print()
function output using various methods. These methods included redirecting the output of a Python script from the command-line, redirecting the standard output within Python scripts, and specifying a file-like object in the file
parameter directly in the print()
function.
This article was written by Jacob Stopak, a software developer and consultant with passion for helping others improve their lives through code. Jacob is the author of the Coding Essentials Guidebook for Developers, an introductory book that covers essential coding concepts and tools. It contains chapters on basic computer architecture, the Internet, Command Line, HTML, CSS, JavaScript, Python, Java, databases/SQL, Git, and more.
How to Write Print Output to a File in Python
Source: https://stackabuse.com/writing-to-a-file-with-pythons-print-function/
0 Response to "How to Write Print Output to a File in Python"
Post a Comment