python 打印输出到文件中
生活随笔
收集整理的這篇文章主要介紹了
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 timeclass Logger(object):def __init__(self, fileN='Default.log'):self.terminal = sys.stdoutsys.stdout = selfself.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.terminaldef flush(self):passfor i in range(3):logger = Logger('./result/temp%s.txt'%i)a=(0,1,2,3)print(a,i) logger.reset()總結
以上是生活随笔為你收集整理的python 打印输出到文件中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ls4278设置说明书
- 下一篇: mercurial hg best pr