python将print的内容输出到txt文件

想起昨天天调试某程序时,打印出的内容太多不方便看,在网上找了个法子将其输入到文件。

import sys


class Logger(object):
def __init__(self, fileN='Default.log'):
self.terminal = sys.stdout
self.log = open(fileN, 'a')

def write(self, message):
'''print实际相当于sys.stdout.write'''
self.terminal.write(message)
self.log.write(message)

def flush(self):
pass


sys.stdout = Logger('G:/2.0/test.txt') # 调用print时相当于Logger().write()

每次调用print都相当于调用Logger().write(),然后做了print本该做的事,打印到控制台,然后将内容保存到指定文件。
原文地址:https://www.cnblogs.com/henry2019/p/14313948.html