How to save python screen output to a text file

前端 未结 10 985
星月不相逢
星月不相逢 2020-12-08 06:16

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         


        
相关标签:
10条回答
  • This is very simple, just make use of this example

    import sys
    with open("test.txt", 'w') as sys.stdout:
        print("hello")
    
    0 讨论(0)
  • 2020-12-08 06:53

    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.

    0 讨论(0)
  • 2020-12-08 06:54

    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.

    0 讨论(0)
  • 2020-12-08 06:54

    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.

    0 讨论(0)
提交回复
热议问题