
To print the value of stderr in the file, we need to redirect it. When any error encounters in Python, it is written to the standard error stream (stderr). Method 2: Redirecting through Standard Error Stream: The sys.stdout = orig_stdout will reset the standard output to its original value. Next, within its body, we will assign the file to the standard output.įinally, whatever string we will pass in the print() function will get written in the file from the standard output. Then, we have to open a file (dataFile) with the write mode and alias it as ‘gr’. Then we create a variable orig_stdout where we initialized the value of sys.stdout. Then, we will print a message that gets displayed on the console output. Print('Writing the codename GR26 to the newly created file.')įirst, we will import the sys module. Print('Displaying this message on the output console.') That is where we can use the print() function with different approaches or parameters. We can also redirect the standard output to other locations, such as text files. The other two streaming pipes are stdin and stderr.īy default, the standard output (stdout) pipe aims at the interactive window that helps in program execution. Apart from printing data to the console, it also helps in sending texts to a location called the standard output stream (stdout). There are various ways and operations that programmers can perform using print(). Python's print() function is more flexible than you can imagine. Method 1: Redirecting the standard output data to a File: This article will talk about how to write to a Python file through the print() function. However, there's a possibility to change its operation from writing to console to writing text to a file. It entirely depends on what the Python program is running.

Developers mostly use it to display strings and variable values each in the interactive interpreter or the compiler. The print() function of Python is one of the most widely used functions.
