Skip to content

How to redirect print output to a text file in Python

How to redirect print output to a text file in python

In this tutorial we will learn how to redirect print output to a text file in Python . But before going further let us have a look at print function in Python .

Syntax of print function

print(objects, sep=separator, end=end, file=filename, flush=flushvalue)

From the above syntax we can see that print() function has a file parameter . By default value of file parameter is sys.stdout . For this reason whenever we print anything it prints on the standard output .

Example :

# printing in the standard output
print("Rajkumar")
Rajkumar

In the above code we have seen that we have printed “Rajkumar” it has been printed on the standard output .

Now using the file parameter we will see how to redirect print output to a text file in Python . For this reason we have to open the file in w or a mode . If the file does not exist it will be created automatically .

Here we will work with file1.txt which is placed in the current folder where we are working now . Content of file1.txt is shown below –

Note :

If we open the file in w mode then all the previous content of the file will be erased and new content will be added from starting position . But if we open the file in a mode then previous content will not be erased and new content will be added after previous content .

How to redirect print output to a text file in Python

Example 1:

with open("file1.txt","w") as fp:
    print("Rajkumar",file=fp)
  • In the above code we have opened file1.txt in w mode and stored the file-object in fp variable . As the file is opened in w mode so all the previous content is erased .
  • After that we have printed Rajkumar in the file specifying the file parameter as fp .

Example 2:

with open("file1.txt","a") as fp:
    print("Rajkumar",file=fp)
  • In the above code we have opened file1.txt in a mode and stored the file-object in fp variable . As the file is opened in a mode so previous content is not erased .
  • After that we have printed Rajkumar in the file specifying the file parameter as fp .
  • As the default value of end parameter is "\n" so the new content is added in the next line .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply