Saving the Output of a Python Program

How to save python screen output to a text file

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.

Saving an output of a program in python as an image

You can use sys to write the output into an svg file and then save it.
First use chess.svg to create the svg file of chess board and then assign svg in some variable and write that data in the file.

import sys
import chess.svg
import chess
board = chess.Board()
boardsvg = chess.svg.board()
outputfile = open('name.svg', "w")
outputfile.write(boardsvg)
outputfile.close()

I hope that helps!

How to save Python script console output to a file?

You can do you something like this:

def custom_print(message_to_print, log_file='output.txt'):
print(message_to_print)
with open(log_file, 'a') as of:
of.write(message_to_print + '\n')

This way you can use custom_print instead of print to be able to both see the result in the console and have the result appended to a log file.

Python script need to save output to text file

Just add

with open('textfile.txt', 'a+') as f:
f.write(ff)

a option is for appending to a file and + means that if the file is not there just create one with the specified name.

EDIT:

def on_press(key):
print ('{0} pressed'.format(key))
with open('textfile.txt', 'a+') as f:
f.write(ff)

EDIT 2:

def on_press(key):
print ('{0} pressed'.format(key))
k = key + '\n'
with open('textfile.txt', 'a+') as f:
f.write(key)

# and in get_titles()
ff= (moment2 + " : " + "Moved T0 : "+ new_title + '\n')
with open('textfile.txt', 'a+') as f:
f.write(ff)


Related Topics



Leave a reply



Submit