print保存为txt_format python

print保存为txt_format python在 Python 中 你可以通过重定向标准输出 sys stdout 来将 print 函数的输出保存到文件中 以下是两种常见的方法 方法一 使用 Logger 类 pythonimport sys class Logger object def init self filename Default log self terminal sys

在Python中,你可以通过重定向标准输出(`sys.stdout`)来将 `print` 函数的输出保存到文件中。以下是两种常见的方法:

方法一:使用 `Logger` 类

python

import sys

class Logger(object):

def __init__(self, filename="Default.log"):

self.terminal = sys.stdout

self.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`

python

import sys

class PrintToFile(object):

def __init__(self, filename="Default.log"):

self.file_path = filename

self.original_stdout = sys.stdout

def __enter__(self):

self.file = open(self.file_path, "a")

sys.stdout = self.file

return self

def __exit__(self, exc_type, exc_val, exc_tb):

sys.stdout = self.original_stdout

self.file.close()

使用 PrintToFile 上下文管理器

with PrintToFile("./log.txt"):

print("hello world!")

注意事项

第一种方法只需要运行一次,之后 `print` 函数的输出就会被保存到指定的文件中。

第二种方法使用了上下文管理器,可以在 `with` 语句块内自动保存输出,并在退出时自动关闭文件。

请确保在程序结束时正确关闭文件,避免资源泄露。

编程小号
上一篇 2026-03-29 20:32
下一篇 2026-03-29 20:26

相关推荐

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