How to save python screen output to a text file

前端 未结 10 1029
星月不相逢
星月不相逢 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条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 06:33

    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.

提交回复
热议问题