python输出到文件
生活随笔
收集整理的這篇文章主要介紹了
python输出到文件
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
通過(guò)改變sys.stdout使結(jié)果輸出到文件。
import sys import osdef mkdir_if_missing(dir_path):try:os.makedirs(dir_path)except OSError as e:if e.errno != errno.EEXIST:raiseclass Logger(object):def __init__(self, fpath=None):self.console = sys.stdoutself.file = Noneif fpath is not None:mkdir_if_missing(os.path.dirname(fpath))self.file = open(fpath, 'w')def __del__(self):self.close()def __enter__(self):passdef __exit__(self, *args):self.close()def write(self, msg):self.console.write(msg)if self.file is not None:self.file.write(msg)def flush(self):self.console.flush()if self.file is not None:self.file.flush()os.fsync(self.file.fileno())def close(self):self.console.close()if self.file is not None:self.file.close()log_path = os.path.join(log_dir, model_id) # 輸出文件的路徑 sys.stdout = Logger(log_path)print('Hello World!') sys.stdout.flush() # 不手動(dòng)flush有時(shí)候很久才刷新總結(jié)
以上是生活随笔為你收集整理的python输出到文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: AAAI 2021 《Regulariz
- 下一篇: websocket python爬虫_p