- Python print() to File
- Python – Print to File
- Method 1: Print To File Using Write()
- Method 2: Redirect sys.stdout to the file
- Method 3: Explicitly print to the file
- Using a context manager
- Method 4: Use the logging module
- References
- Writing to a File with Python’s print() Function
- Redirecting a Python’s Script Output in the Terminal
- Redirecting the Standard Output Stream
- Free eBook: Git Essentials
- Redirecting the Standard Error Stream
- Print Using the «file» Parameter
- Conclusion
- About the Author
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()
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.
The script output is in the file.
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('Hi') f.write('Hello from AskPython') f.write('exit')
Output (Assume that output.txt is a newly created file)
[email protected]:~# python output_redirection.py Hi Hello from AskPython exit [email protected]:~# cat output.txt Hi Hello from AskPython exit
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 sys.stdout.close() # 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 output_redirection.py Hi Hello from AskPython exit [email protected]:~# cat output.txt Hi Hello from AskPython exit
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') logging.info('Hello from AskPython') logging.warning('exit')
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.
References
Writing to a File with Python’s print() Function
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:
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:
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:
Free eBook: Git Essentials
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!
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
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.
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.
About the Author
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.