How to Print to File in Python?

Python print to file

We use the print() function in python to print any text to standard output. In this article, we will see how we can use the print() function to directly print an output to a file. For this, we will first discuss the print() function and then we will see how we can print to file in python using the print() function.

The print() function in python

Normally, we use the print() function to print different objects by passing one or more objects to the function as input argument as follows.

Output:

Apart from the objects to print, the print() function has five other parameters. To learn about them, let us look at the syntax of the print() function.

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

Here,

  • The objects are the objects that we normally pass to the print() function to print.
  • The sep parameter takes an input argument separator. It is an optional parameter and the separator has a default value of whitespace “ ”. This is why the print() function prints all the objects with whitespace between them.
  • The end parameter takes an input argument end to specify what should it print after printing all the objects. It is an optional parameter and the argument end has a default value “\n” i.e. newline.
  • The file parameter is used to print the values of objects to an output stream. Here, the object passed in as the file argument must have a write() method. The parameter file is also an optional parameter and the input argument file has a default value sys.stdout. This is why the print() function writes the values in the objects to the standard output by default.
  • The flush parameter is used to tell the print() function if the output is flushed (True) or buffered (False). It is also an optional parameter and the flush argument has a default value False.

How to Print to file in python?

To print to file in python, we will have to direct the print() function to print the output to the file using the file parameter discussed above. We can also redirect the standard output stream to the file object by using the sys module. Let us discuss both these approaches one by one.

Print to file using the file parameter in the print function

To print the output of the print() function to a file, we will first open a file in write mode using the open() function. The open() function takes a file name and mode as input arguments and returns a file object after successfully opening the file. Here, we will pass the file name as the first input argument to the open() function. We will use the file in write mode by using “w” as the second input argument to the open() function.

You should keep in mind that the open() function will erase the contents of any existing file with the same file name after opening it when we use the write mode. If there exists no file with the given file name, the open() function will create a new empty file.

After opening the file, we will pass the file object as an input argument to the file parameter of the print() function. In this way, the output of the print() function will be written to the file. 

After writing to the file, Don’t forget to close the file using the close() method. Otherwise, the changes will not be saved.

The python code for this entire process is given below.

After printing contents to the file, you can open the file in the read mode to verify the contents of the file as shown below.

Output:

Print to file by redirecting standard output

Instead of using the file parameter, we can use the sys module to divert the standard output to the file. For this, We will use the following steps.

  • First, we will open the file using the open() function. The open() function returns a file object that we will keep in a variable named myFile.
  • After that, we will assign the file object myFile to the standard output stream sys.stdout.
  • After this, whenever we will use the print() statement, the function will print the output to the file.

You should keep in mind that sys.stdout is a default environment variable. So, we should not change its value. Therefore, we will store the value of sys.stdout in a variable, and after printing contents to the file, we will assign the default value to sys.stdout. After assigning the default value to sys.stdout, you should also close the file using the close() method. Otherwise, the contents written in the file will not be saved.

The following python code prints contents to a file by redirecting the standard output.

After closing the file, you can open the file in the read mode to verify the contents of the file as shown below.

Output:

Conclusion

In this article, we have discussed the syntax of the print() statement. After that, we have discussed two ways to print contents directly to a file using the print() function. I would suggest you use the approach with the print() function and the file parameter as it doesn’t require you to change the environment variables. If you will use the second approach by changing the environment variables, you might forget to revert back the changes and it may cause errors in your programs.

I hope you enjoyed reading this article. Stay tuned for more informative articles. 

Happy Learning!

Related Posts

  • Python absolute path
    17 November

    Get Absolute Path in Python

    Table of ContentsWhat is an absolute path to a file? How to get absolute path in PythonUse abspath to get the absolute path to file use pathlib module to get the absolute path to file Conclusion We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Python print type of variable
    16 November

    Print type of variable in Python

    Table of ContentsWhat is the type of variable in Python?Ways to print type of variable in PythonUsing the type() functionUsing the isinstance() functionUsing the __class__() functionConclusion What is the type of variable in Python? We use variables to store data in a reserved memory location. The type of a variable defines the memory allocated to […]

  • Python float array to int
    11 November

    Convert float array to int array in Python

    Table of ContentsWhat are the types of arrays?Ways to convert float arrays to int in PythonUsing the numpy.asarray() functionUsing the numpy.astype() functionUsing the numpy.int_() functionUsing the numpy.round_() functionUsing the numpy.rint() functionUsing the numpy.floor() functionUsing the numpy.ceil() functionUsing the numpy.trunc() functionConclusion What are the types of arrays? An array is a common structure that stores multiple […]

  • List intersection in Python
    11 November

    List intersection in python

    Table of ContentsWhat is the list intersection in Python?Ways to find the list intersection in PythonUsing the for loop to achieve list intersection in PythonUsing the set() function to find list intersection in PythonUsing the intersection() function to find list intersection in PythonUsing the filter() and lambda functions to find list intersection in PythonUsing the […]

  • Bilinear Interpolation in Python
    11 November

    Bilinear Interpolation in Python

    Table of ContentsWhat is Bilinear Interpolation?Creating a function to perform bilinear interpolation in PythonUsing the scipy.interpolate.interp2d() function to perform bilinear interpolation in Python What is Bilinear Interpolation? Linear Interpolation in mathematics helps curve fitting by using linear polynomials that make new data points between a specific range of a discrete set of definite data points. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.