在Python中,你可以通过重定向标准输出(`sys.stdout`)来将 `print` 函数的输出保存到文件中。以下是两种常见的方法:
方法一:使用 `Logger` 类
import sysclass Logger(object):def __init__(self, filename="Default.log"):self.terminal = sys.stdoutself.log = open(filename, "a", encoding="utf-8")def write(self, message):self.terminal.write(message)self.log.write(message)def flush(self):pass使用 Logger 类if __name__ == "__main__":sys.stdout = Logger("./log.txt")print("hello world!")
方法二:使用上下文管理器 `PrintToFile`
import sysclass PrintToFile(object):def __init__(self, filename="Default.log"):self.file_path = filenameself.original_stdout = sys.stdoutdef __enter__(self):self.file = open(self.file_path, "a")sys.stdout = self.filereturn selfdef __exit__(self, exc_type, exc_val, exc_tb):sys.stdout = self.original_stdoutself.file.close()使用 PrintToFile 上下文管理器with PrintToFile("./log.txt"):print("hello world!")
注意事项
第一种方法只需要运行一次,之后 `print` 函数的输出就会被保存到指定的文件中。
第二种方法使用了上下文管理器,可以在 `with` 语句块内自动保存输出,并在退出时自动关闭文件。
请确保在程序结束时正确关闭文件,避免资源泄露。

