How to save python screen output to a text file

前端 未结 10 1031
星月不相逢
星月不相逢 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:43

    I found a quick way for this:

    log = open("log.txt", 'a')
    
    def oprint(message):
        print(message)
        global log
        log.write(message)
        return()
    
    code ...
    
    log.close()
    

    Whenever you want to print something just use oprint rather than print.

    Note1: In case you want to put the function oprint in a module then import it, use:

    import builtins
    
    builtins.log = open("log.txt", 'a')
    

    Note2: what you pass to oprint should be a one string (so if you were using a comma in your print to separate multiple strings, you may replace it with +)

提交回复
热议问题