Python print save to file

Python Print to File

We always use print statements in Python to display the output in the console or command line terminal. However, sometimes we want to change this behavior to print to a text file instead of the console.

The print() method accepts the file parameter as one of the arguments, and using this, we can print the standard output to a file.

The default value of the file argument is sys.stdout , which prints the output on the screen.

Example 1: Print to the text file

The below program opens the existing text file in the write mode using the open() function (if file is not available it will create a new file) and writes all the text specified inside the print statement. Once the content is written to a file, we close the file using the close() method.

# Print to the text file file = open('log.txt', 'w') print('This is a sample print statement', file = file) print('Hello World', file = file) file.close()
This is a sample print statement Hello World 

Example 2: Print to the text file using inline file argument

If you want to control only a few print statements to output to a text file, you could inline the file argument inside the print statement, as shown below.

# Appends the print statement into a log.txt print("Welcome to ItsMyCode", file=open('log.txt','a')) 

Redirecting the Standard Output Stream to a file

Specifying the file argument helps debug the smaller programs but is not desirable in some situations.

Читайте также:  Что такое first питон

In this case, we can redirect all the standard output stream to a file. Setting the standard output to a file ensures that the text specified inside the print() function will be written to a file instead of displaying in the console.

The standard output can be set in Python by importing the sys module and setting the stdout to a file or file-like object.

import sys # Prints in a console/terminal print('Default mode: Prints on a console.') # Store the reference of original standard output into variable original_stdout = sys.stdout # Create or open an existing file in write mode with open('log.txt', 'w') as file: # Set the stdout to file object sys.stdout = file print('File Mode: Print text to a file.') # Set the stdout back to the original or default mode sys.stdout = original_stdout print('Default Mode: Prints again on a console.') 
Hello Welcome to Python Tutorials . File Mode: Print text to a file. 
Default mode: Prints on a console. Default Mode: Prints again on a console.

Redirect the Python Script Output to File

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

For example, if you have a Python script file named main.py with the following code.

We can redirect the output of the Python script using the right angle bracket, as shown below.

python3 main.py > output.txt

If you open the output.txt file, you can see the below content written into the text file.

Источник

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.

Источник

Python – Print to File

In this article, we shall look at some of the ways to use Python to print to file.

Method 1: Print To File Using Write()

We can directly write to the file using the built-in function write() that we learned in our file handling tutorial.

with open('output.txt', 'a') as f: f.write('Hi') f.write('Hello from AskPython') f.write('exit')

Output (Assume that output.txt is a newly created file)

[email protected]:~# python output_redirection.py Hi Hello from AskPython exit [email protected]:~# cat output.txt Hi Hello from AskPython exit

Method 2: Redirect sys.stdout to the file

Usually, when we use the print function, the output gets displayed to the console.

But, since the standard output stream is also a handler to a file object, we can route the standard output sys.stdout to point to the destination file instead.

The below code is taken from our previous article on stdin, stdout and stderr. This redirects the print() to the file.

import sys # Save the current stdout so that we can revert sys.stdou after we complete # our redirection stdout_fileno = sys.stdout sample_input = ['Hi', 'Hello from AskPython', 'exit'] # Redirect sys.stdout to the file sys.stdout = open('output.txt', 'w') for ip in sample_input: # Prints to the redirected stdout (Output.txt) sys.stdout.write(ip + '\n') # Prints to the actual saved stdout handler stdout_fileno.write(ip + '\n') # Close the file sys.stdout.close() # Restore sys.stdout to our old saved file handler sys.stdout = stdout_fileno

Output (Assume that output.txt is a newly created file)

[email protected]:~# python output_redirection.py Hi Hello from AskPython exit [email protected]:~# cat output.txt Hi Hello from AskPython exit

Method 3: Explicitly print to the file

We can directly specify the file to be printed in the call to print() , by mentioning the file keyword argument.

For example, the below snippet prints to the file output.txt .

print('Hi', file=open('output.txt', 'a')) print('Hello from AskPython', file=open('output.txt', 'a')) print('exit', file=open('output.txt', 'a'))

The file now has the three lines appended to it, and we have successfully printed to output.txt !

Using a context manager

However, this method isn’t the best way to resolve this situation, due to the repeated calls to open() on the same file. This wastes time, and we can do better!

The better way would be to explicitly use a context manager with statement, which takes care of automatically closing the file and using the file object directly.

with open("output.txt", "a") as f: print('Hi', file=f) print('Hello from AskPython', file=f) print('exit', file=f)

This gives the same result as before, appending the three lines to output.txt , but is now much faster, since we don’t open the same file again and again.

Method 4: Use the logging module

We can use Python’s logging module to print to the file. This is preferred over Method 2, where explicitly changing the file streams is not be the most optimal solution.

import logging # Create the file # and output every level since 'DEBUG' is used # and remove all headers in the output # using empty format='' logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='') logging.debug('Hi') logging.info('Hello from AskPython') logging.warning('exit')

This will, by default, append the three lines to output.txt . We have thus printed to the file using logging , which is one of the recommended ways of printing to a file.

References

Источник

Оцените статью