I\'m new to Python. I need to query items from a dict and save the result to a text file. Here\'s what I have:
import json
import exec.fullog as e
input = e
This is very simple, just make use of this example
import sys
with open("test.txt", 'w') as sys.stdout:
print("hello")
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.
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.