Write File with print() Function In Python

Python provides the print() function in order to print or display some text to data in the command-line interface or interactive interpreter. Event the print() function is mostly used to print command-line interfaces or interactive interpreters there are some alternatives that can be used to write a file. In this tutorial, we examine how to write into a file by using the print() function.

Redirect Python Output To A File

The most basic way in order to print into a file using the print() function is running the Python script file and redirecting the output into a file. The > operator is used to redirect output into the specified file for the Linux bash. The Python script can be called by using the python3 interpreter or making the Python script directly executable.

#!/bin/python3

print("Hello Pythontect")

This script can be called like below by using the python3 command or interpreter and the output is redirected into file named output.txt .

$ python3 hello.py > output.txt

Redirect Standard Output Stream (stdout) To File

Linux bash provides the Standard Output Stream or stdout which is used for running process to put output by default. This is the current command line interaface or shell by default. But the standard output stream can be changed into a file where the print() function put provided text or data into stdout which is a file.

import sys

with open("output.txt","w") as f:
   sys.stdout = f
   print("Hello Pythontect")

Use File Descriptor

The print() function is used to print to stdout by defdault but the file descriptor can be used to set the default stdout as a file. The print() function accepts the file parameter where an opened file descriptor can be set and the printed text or data can be put inside this file. This method is most convenient, simple and easy to understand way to print into a file.

import sys

with open("output.txt","w") as f:
   print("Hello Pythontect",file=f)

Leave a Comment