微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python 打印输出到文件中

目录

方法一: 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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐