目录
方法一: print函数中指定 file 参数
方法二:指定 sys.stdout
方法一: print
函数中指定 file
实例:
with open('/Users/xz/test/1.txt', 'a+') as f:
print('Hello World!', file=f)
实例2:
with open('C:\\Users\\abc\\Desktop\\saveOrUpdate.sql', 'a+', encoding='utf-8') as f:
print("hello world", file=f)
方法二:指定 sys.stdout
实例:
import sys
import time
class Logger(object):
def __init__(self, fileN='Default.log'):
self.terminal = sys.stdout
sys.stdout = self
self.log = open(fileN, 'w')
def write(self, message):
'''print实际相当于sys.stdout.write'''
self.terminal.write(message)
self.log.write(message)
def reset(self):
self.log.close()
sys.stdout=self.terminal
def flush(self):
pass
for i in range(3):
logger = Logger('./result/temp%s.txt'%i)
a=(0,1,2,3)
print(a,i)
logger.reset()