python-將print內容保存到文件的3種方式


通過sys.stdout得到print輸出的內容,再進行保存

方式一: 一次運行

import sys


class Logger(object):
    def __init__(self, file_path: str = "./Default.log"):
        self.terminal = sys.stdout
        self.log = open(file_path, "a", encoding="utf-8")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass


if __name__ == '__main__':
    sys.stdout = Logger('./log.txt')
    print('hello world!')

這種方法只需要運行一次,之后就可以直接使用print函數來保存內容,但如果程序中途出錯可能出現部分內容丟失。

方式二: 多一個步驟

import sys


class PrintToFile(object):
    def __init__(self, file_path: str = "./Default.log"):
        self.file_path = file_path
        self.original_stdout = sys.stdout

    def __enter__(self):
        self.file = open(self.file_path, 'a', encoding="utf-8")
        sys.stdout = self.file
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        sys.stdout = self.original_stdout
        self.file.close()


if __name__ == '__main__':
    with PrintToFile('./log.txt'):
        print("Hello, world!")

這種方式可以及時保存內容,但要把print寫在with的作用域內。

方式三: 重寫print函數

# 保存原始的 print 函數
rewrite_print = print
# 定義新的 print 函數
def print(*arg):
    file_path = './log.txt'
    # 打印到控制台
    rewrite_print(*arg)
    # 保存到文件
    rewrite_print(*arg, file=open(file_path, "a", encoding="utf-8"))


if __name__ == '__main__':
    print("Hello, world!")

在任意地方導入這個函數就可以實現了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM