Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save python screen output to a text file

I'd like to query items from a dict and save the printed output to a text file.

Here's what I have:

import json
import exec.fullog as e

inp = e.getdata() #inp now is a dict() which has items, keys and values.

#Query

print('Data collected on:', inp['header']['timestamp'].date())
print('\n CLASS 1 INFO\n')

for item in inp['Demographics']:
    if item['name'] in ['Carly', 'Jane']:
        print(item['name'], 'Height:', item['ht'], 'Age:', item['years'])

for item in inp['Activity']:
    if item['name'] in ['Cycle', 'Run', 'Swim']:
        print(item['name'], 'Athlete:', item['athl_name'], 'Age:', item['years'])
like image 357
Ironfist Avatar asked Jul 29 '14 19:07

Ironfist


People also ask

How do I save Python output to a text file?

First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do you save a text file as output?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do you create an output file in Python?

To create and write to a new file, use open with “w” option. The “w” option will delete any previous existing file and create a new file to write. If you want to append to an existing file, then use open statement with “a” option. In append mode, Python will create the file if it does not exist.


2 Answers

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.
like image 179
Boris Gorelik Avatar answered Oct 17 '22 04:10

Boris Gorelik


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.

like image 28
ZZZ Avatar answered Oct 17 '22 04:10

ZZZ