Print into file python

How to save python screen output to a text file

Simply, continue printing whatever you want, to the cosole just like you do using print or log within the Python file; no specific change here. Now, while executing the python file python3 yo.py , simply replace the command with python3 yo.py > logs.txt

12 Answers 12

A quick and dirty hack to do this within the script is to direct the screen output to a file:

import sys stdoutOrigin=sys.stdout sys.stdout = open("log.txt", "w") 

and then reverting back to outputting to screen at the end of your code:

sys.stdout.close() sys.stdout=stdoutOrigin 

This should work for a simple code, but for a complex code there are other more formal ways of doing it such as using Python logging.

abarnert ‘s answer is very good and pythonic. Another completely different route (not in python) is to let bash do this for you:

$ python myscript.py > myoutput.txt 

This works in general to put all the output of a cli program (python, perl, php, java, binary, or whatever) into a file, see How to save entire output of bash script to file for more.

If you want the output to go to stdout and to the file, you can use tee:

$ python myscript.py | tee myoutput.txt 

Actually, this is even more universally usable: simple > redirection works on Windows, and on almost all *nix shells, not just bash.

Thanks @abarnert, I’m blissfully unaware of Windows cmd, but I sit ~100ft from one of the creators of tcsh so I definitely should have known better. I’ve updated to reflect your info.

Well, cmd.exe is meant to be a superset of DOS command.com, which is a clone of the CP/M CCP with some minor changes, and I’ll bet someone in your office at least has vague recollections of that. 🙂

Let me summarize all the answers and add some more.

  • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open(‘file.txt’, ‘w’) stuff.
  • If don’t want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt stuff.
  • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don’t want to modify your program, you may use the tee command (windows version also exists, but I have never used it)
  • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.
Читайте также:  Python sys not defined

What you’re asking for isn’t impossible, but it’s probably not what you actually want.

Instead of trying to save the screen output to a file, just write the output to a file instead of to the screen.

with open('outfile.txt', 'w') as outfile: print >>outfile, 'Data collected on:', input['header']['timestamp'].date() 

Just add that >>outfile into all your print statements, and make sure everything is indented under that with statement.

More generally, it’s better to use string formatting rather than magic print commas, which means you can use the write function instead. For example:

outfile.write('Data collected on: <>'.format(input['header']['timestamp'].date())) 

But if print is already doing what you want as far as formatting goes, you can stick with it for now.

What if you’ve got some Python script someone else wrote (or, worse, a compiled C program that you don’t have the source to) and can’t make this change? Then the answer is to wrap it in another script that captures its output, with the subprocess module. Again, you probably don’t want that, but if you do:

output = subprocess.check_output([sys.executable, './otherscript.py']) with open('outfile.txt', 'wb') as outfile: outfile.write(output) 

You would probably want this. Simplest solution would be

in case you want to append to file

Now, write to the same file via

Close the file after you are done using it

Here’s a really simple way in python 3+:

f = open('filename.txt', 'w') print('something', file = f) 

This is very simple, just make use of this example

import sys with open("test.txt", 'w') as sys.stdout: print("hello") 
python script_name.py > saveit.txt 

Because this scheme uses shell command lines to start Python programs, all the usual shell syntax applies. For instance, By this, we can route the printed output of a Python script to a file to save it.

I found a quick way for this:

log = open("log.txt", 'a') def oprint(message): print(message) global log log.write(message) return() code . log.close() 

Whenever you want to print something just use oprint rather than print.

Note1: In case you want to put the function oprint in a module then import it, use:

import builtins builtins.log = open("log.txt", 'a') 

Note2: what you pass to oprint should be a one string (so if you were using a comma in your print to separate multiple strings, you may replace it with +)

We can simply pass the output of python inbuilt print function to a file after opening the file with the append option by using just two lines of code:

with open('filename.txt', 'a') as file: print('\nThis printed data will store in a file', file=file) 

Hope this may resolve the issue.

Note: this code works with python3 however, python2 is not being supported currently.

idx = 0 for wall in walls: np.savetxt("C:/Users/vimal/OneDrive/Desktop/documents-export-2021-06-11/wall/wall_"+str(idx)+".csv", wall, delimiter=",") idx += 1 
class Logger: def __init__(self, application_log_file, init_text="Program started", print_with_time=True): import sys self.__output_num = 0 self.origin = sys.stdout self.init_text = init_text self.__init = False self.print_with_time = print_with_time self.log_file = application_log_file self.data = "" self.last_time = 0 sys.stdout = self sys.stderr = self def flush(self): if self.data == "\n": return sys.stdout = self.origin print(self.__create_log_text(self.data) if self.print_with_time else self.data) with open(self.log_file, "a", encoding="utf-8") as log: log.write(self.__create_log_text(self.data)) self.data = "" sys.stdout = self def __create_log_text(self, string: str): if self.last_time == str(datetime.datetime.today())[:-7]: return string self.last_time = str(datetime.datetime.today())[:-7] if not self.__init: self.__init = True return str(datetime.datetime.today())[:-7] + " | " + f"\n" return str(datetime.datetime.today())[:-7] + " | " + string def write(self, data): self.data += data 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Html link rel help

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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!

Читайте также:  Php для web сервера

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

Источник

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.

Источник

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