There is a case when you want to output the results to the text file. How you can do so? In this entire tutorial, you will know how to get the python output in a text file using various methods.
Steps to get python output in a text file
Let’s know all the steps that you will follow to get the python output in a text file. Just follow all the steps given below for more understanding.
Step 1: Create a sample program
The first step is to create a sample program that will be used to output the results to the text file. The following program will print out a sample list.
list = [10,20,30,40] print(list)
Step 2: Use the following methods to get python output in a text file
In this step, you will know all the methods that you will use to get the output to the text file in python.
Method 1: Using the >> operator
Suppose you have a python script file and want to save its output to the text file. You can use the >> operator to output the results. Just open the command prompt and type the following command to save the output as a text file.
Method 2:Using print() function with file argument
The other method to output the results to the text file is the use of the print() function. Additionally, with the print() function, you will pass the file argument. The results will be written to the file name f.
Run the below lines of code to achieve the above task.
list = [10,20,30,40] with open('output.txt', 'w') as f: print(list, file=f)
Method 3:Using the sys.stdout redirection
The third method is the use of sys.stdout redirection. The sys.stdout variable is assigned to the file f instead of the console output. Use the below lines of code to output the results to the text file.
import sys list = [10,20,30,40] with open('output.txt', 'w') as f: sys.stdout = f print(list) sys.stdout = sys.__stdout__
Method 4: Use the logging module
You can also use the logging module to output the results to the text. Here you will use logging.debug() function with the logging.basicConfig() to configure the logging output to the text file “output.txt”.
Execute the below lines of code.
import logging list = [10,20,30,40] logging.basicConfig(filename='output.txt', level=logging.DEBUG) logging.debug(list)
DEBUG:root:[10, 20, 30, 40]
It’s better that you should output the results to the text file. And is widely common among developers that want to know what happened to the program in the future. Most of the deployer use logs on the server to continuously monitor the programs to understand whether it is running or not. The above methods allow you to output the results to the text file.
I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.