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!


import_contacts

You may also like:

Related Posts

  • Make requirements.txt in Python
    03 May

    Make requirements.txt in python

    Table of ContentsWhat is the requirements.txt file in Python?Ways to make requirements.txt file in PythonUsing the pip to make requirements.txt in PythonUsing the conda command to make requirements.txt file in PythonUsing the pipreqs package to make requirements.txt file in PythonConclusion What is the requirements.txt file in Python? Every package is also updated regularly and features […]

  • Create an array of 1 to 10 in Python
    03 May

    Create an Array of 1 to 10 in Python

    Table of ContentsIntroductionHow to create an array of 1 to 10 in Python?Using the range() function to create an array of 1 to 10 in Python.Using list comprehension along with the range() function to create an array of 1 to 10 in Python.Using a user-defined function to create an array of 1 to 10 in […]

  • Remove Urls from String in Python
    03 May

    Remove Urls from Text in Python

    Table of ContentsIntroductionWays to remove URLs from Text in PythonUsing the re.sub() function to remove URLs from Text in PythonUsing the re.findall() function to remove URLs from Text in PythonUsing the re.search() function to remove URLs from Text in PythonUsing the urllib.urlparse class to remove URLs from Text in PythonConclusion In this post, we will […]

  • Create a list from 1 to 100 in Python
    03 May

    Create a List from 1 to 100 in Python

    Table of ContentsWays to create a list from 1 to 100 in PythonUsing the range() function to create a list from 1 to 100 in PythonUsing the numpy.arange() function to create a list from 1 to 100 in PythonUsing the for loop with range() to create a list from 1 to 100 in PythonConclusion In […]

  • Return vs Print in Python
    16 April

    Return vs Print in Python

    Table of ContentsReturn vs Print in PythonConclusion Return vs Print in Python In Python, we work with a wide range of functions that make our code simple. We can also create functions using the def keyword. A function can be defined as per our requirement and can display something or return a value. This is […]

  • Floor division in Python
    10 April

    Floor division in Python

    Table of ContentsWhat is Floor Division in Python?How to implement floor division in Python?Using the // operator to implement floor division in Python.Using the // operator to implement floor division on negative integers in Python.Using the // operator to implement floor division on floating-point numbers in Python.Using the // operator to implement floor division with […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.