Python output to file windows

Python print() to File

Learn to use Python print() function to redirect the print output of a Python program or Python script to a file.

1. Print to File using file Argument

The print() function accepts 5 keyword arguments apart of the objects to print on the standard output (by default, the screen). One such keyword argument is file.

The default value of the file argument is sys.stdout which prints the output on the screen. We can specify any other output target which must be an object with write(string) method.

The given Python program opens the demo.txt in writing mode and write the test ‘Hello, Python !’ into the file.

sourceFile = open('demo.txt', 'w') print('Hello, Python!', file = sourceFile) sourceFile.close()

2. Redirecting Standard Output Stream to a File

Specifying the file parameter in all print() statements may not be desirable in some situations. We can temporarily redirect all the standard output streams to a file in this case.

Once all the required objects are written in the File, we can redirect the standard output back to the stdout .

import sys # Saving the reference of the standard output original_stdout = sys.stdout with open('demo.txt', 'w') as f: sys.stdout = f print('Hello, Python!') print('This message will be written to a file.') # Reset the standard output sys.stdout = original_stdout print('This message will be written to the screen.')

The program outputs to the file after setting the standard output to the file.

Hello, Python! This message will be written to a file.

The program again outputs to the console after resetting the standard putout target.

This message will be written to the screen.

3. Redirecting Script Output to File

Another way to redirect the output is directly from the command line while executing the Python script. We can use > character to output redirection.

The script output is in the file.

Источник

Writing to a File with Python’s print() Function

Python’s print() function is typically used to display text either in the command-line or in the interactive interpreter, depending on how the Python program is executed. However, we can change its behavior to write text to a file instead of to the console.

In this article, we’ll examine the many ways we can write to a file with the print() function.

Redirecting a Python’s Script Output in the Terminal

The quick and dirty way to redirect a Python script’s output is directly from the command-line while executing the script.

For example, if we had a Python file called hello.py with the following contents:

print("Hallo") # Deliberately in German 

We can redirect the output of the file in the shell using a single right angle bracket:

$ python3 hello.py > output.txt 

If we open our newly created output.txt , we’ll see the following contents:

However, with this method, all output of the script is written to a file. It is often more flexible to perform this redirection from within the Python script itself.

Redirecting the Standard Output Stream

In Python, the print() function is more flexible than you might think. It was not hard-coded in such a way that specified text can only be written to the display. Instead, it sends text to a location called the standard output stream, also known as stdout .

All UNIX systems have three main pipes — standard input pipe ( stdin ), standard output pipe ( stdout ) and standard error pipe ( stderr ).

By default, the standard output pipe points to the interactive window used to execute the program, so we normally see text printed out on the screen. However, the standard output can be redirected to other locations, such as files, for convenience.

If the standard output is redirected to a specific file, the text specified in the print() function will be written to that file instead of being displayed on the screen.

In Python, a reference to the standard output can be obtained using the stdout object of the sys module. It is a file-like object, meaning it has methods that allow Python to read and write from it like an actual file.

Let’s see an example where we change stdout to be a file:

import sys print('This message will be displayed on the screen.') original_stdout = sys.stdout # Save a reference to the original standard output with open('filename.txt', 'w') as f: sys.stdout = f # Change the standard output to the file we created. print('This message will be written to a file.') sys.stdout = original_stdout # Reset the standard output to its original value 

The print() function takes the supplied string argument, appends a newline character to the end, and calls the stdout.write() method to write it to standard output.

In the example above, we first print a line of text as we’re accustomed to, which will be displayed in the console when we run the file. We then reassigned stdout to our custom file object — f . Since a file object has a perfectly valid write() method, our printed value gets written to the file without a problem.

Note that it is good practice to store the original value of the standard output in a variable before changing it. This way we can reset the standard output to its original value after we’re done, which can help avoid confusion.

Let’s save the code to a new file, printToFile.py . And then, let’s execute it:

We’ll see the following output in the Terminal:

This message will be displayed on the screen. 

And the script will create a new file called filename.txt with the following contents:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This message will be written to a file. 

You successfully redirected data from the standard output stream to a file. Let’s see how we can do this to another popular file-like object that’s dedicated to programming errors.

Redirecting the Standard Error Stream

In Python, errors are written to the standard error stream, also known as stderr . This also defaults to the interactive window but can be changed via the sys.stderr object. If we wanted to print values to the stderr , we could simply redirect the sys.stdout to point to the sys.stderr .

Create a file called printToStderr.py and add the following code:

import sys print('This message will be displayed via standard output.') original_stdout = sys.stdout # Save a reference to the original standard output sys.stdout = sys.stderr # Redirect the standard output to the standard error. print('This message will be displayed via the standard error.') sys.stdout = original_stdout # Reset the standard output to its original value 

This example is almost identical to the previous one, except that instead of redirecting the standard output stream to a file, we redirect it to the standard error stream. If the standard error stream was also redirected somewhere else, the output would be sent to that location instead of to the screen.

This message will be displayed via standard output. This message will be displayed via the standard error. 

While it may appear like regular output to us, for the computer it is displayed through different pipelines.

In the previous examples, we explicitly redirected the standard output to another file-like object by changing the stdout object. However, for convenience we can do this directly from within the print() function by specifying the output location with the file parameter:

For example, if we wanted to print directly to a file without changing the entire script’s stdout , we would write:

import sys print('This message will be displayed on the screen.') with open('filename.txt', 'w') as f: print('This message will be written to a file.', file=f) 

As we did not fiddle with redirecting the standard output explicitly, we no longer have to reset it to its initial value. As a result, this is the preferred way to write to a file with the print() function.

Note: Although the parameter’s name is file , remember that it works with any file-like object. If you wanted to print to stderr , for example, you would change the print() statement to:

print('This message will be written to stderr.', file=sys.stderr) 

Conclusion

In this article, we discussed redirecting Python’s print() function output using various methods. These methods included redirecting the output of a Python script from the command-line, redirecting the standard output within Python scripts, and specifying a file-like object in the file parameter directly in the print() function.

About the Author

This article was written by Jacob Stopak, a software developer and consultant with passion for helping others improve their lives through code. Jacob is the author of the Coding Essentials Guidebook for Developers, an introductory book that covers essential coding concepts and tools. It contains chapters on basic computer architecture, the Internet, Command Line, HTML, CSS, JavaScript, Python, Java, databases/SQL, Git, and more.

Источник

Redirect Print Output to a File in Python

Redirect Print Output to a File in Python

  1. Use the write() Function to Print Output to a File in Python
  2. Use the print() Function to Print Output to a File in Python
  3. Use sys.stdout to Print Output to a File in Python
  4. Use the contextlib.redirect_stdout() Function to Print Output to a File in Python

There is one more kind of task in file handling that can be done using python i.e redirecting output to an external file. Basically, a standard output can be printed to a file that is chosen by the user itself. There are many ways to carry this out.

In this tutorial, we will see some methods to redirect output to a file in Python.

Use the write() Function to Print Output to a File in Python

This is a built-in Python function that helps in writing or adding a specified text into a file. w and a are the 2 operations in this function that will write or add any text in a file. w is used when the user wants to empty the file before writing anything in it. Whereas a is used when the user just wants to add some text to the existing text in the file.

with open("randomfile.txt", "a") as o:  o.write('Hello')  o.write('This text will be added to the file') 

Note that open() function is used here to open the file. a in the code denotes that text is been added to the file.

Use the print() Function to Print Output to a File in Python

In this method, first, we call the open() function to open the desired file. After that print() function is used to print the text in the file. It is always the user’s choice to either use the w operator or the a operator.

with open("randomfile.txt", "w") as external_file:  add_text = "This text will be added to the file"  print(add_text, file=external_file)  external_file.close() 

Note that the close() function is also used to close the file in the above code after opening it with the open() . After calling the close() function, the file cannot be read and nothing else can be written. If the user tries to make any change in the file after calling the close() function, an error will be raised.

Use sys.stdout to Print Output to a File in Python

The sys module is a built-in Python module that is used by the user to deal with various parts of the runtime environment in Python. To use the sys.stdout , the sys module needs to be imported first.

sys.stdout is used when the user wants to display the output directly to the main console of the screen. The form of the output can be varied, for example, it can be a prompt for input, a print statement, or just an expression. In this method, we will print a statement in a text file.

import sys  file_path = 'randomfile.txt' sys.stdout = open(file_path, "w") print("This text will be added to the file") 

Note that before using the sys.stdout as an object to open and print the statement in the text file, a definite path of the file must be defined by the user otherwise, none of the operations can be performed on the file.

Use the contextlib.redirect_stdout() Function to Print Output to a File in Python

contextlib module is generally used with the with statement.

contextlib.redirect_stdout() function helps to redirect the sys.stdout to some file on a temporary basis by setting up a context manager.

import contextlib  file_path = 'randomfile.txt' with open(file_path, "w") as o:  with contextlib.redirect_stdout(o):  print("This text will be added to the file") 

As you can see, the with statement is used with the operations of contextlib module.

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.

Related Article — Python Print

Источник

Читайте также:  Select стилизация css jquery
Оцените статью