python 将print输出的内容保存到txt文件中

yipeiwu_com5年前Python基础

具体代码如下所示:

import sys
import os
class Logger(object):
  def __init__(self, filename="Default.log"):
    self.terminal = sys.stdout
    self.log = open(filename, "a")
  def write(self, message):
    self.terminal.write(message)
    self.log.write(message)
  def flush(self):
    pass
path = os.path.abspath(os.path.dirname(__file__))
type = sys.getfilesystemencoding()
sys.stdout = Logger('a.txt')
print(path)
print(os.path.dirname(__file__))
print('------------------')

总结

以上所述是小编给大家介绍的python 将print输出的内容保存到txt文件中,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python中用于转换字母为小写的lower()方法使用简介

 lower()方法返回所有基于大小写的字符被转换为小写字符串的一个副本。 语法 以下是lower()方法的语法: str.lower() 参数  &...

各种Python库安装包下载地址与安装过程详细介绍(Windows版)

各种Python库安装包下载地址与安装过程详细介绍(Windows版)

在用Python开发时(Windows环境),会碰到需要安装某个版本的第三方库,为了以后查找、安装方便,总结如下: windows版的各种Python库安装包下载地址: http://w...

Python 面试中 8 个必考问题

1、下面这段代码的输出结果是什么?请解释。 def extendList(val, list=[]): list.append(val) return list list...

Python实现一个简单的验证码程序

  老师讲完random函数,自己写的,虽然和老师示例的不那么美观,智能,但是也自己想出来的,所以记录一下,代码就需要自己不断的自己练习,实战,才能提高啊!不然就像我们这些大部分靠自学的...

python基础_文件操作实现全文或单行替换的方法

python修改文件时,使用w模式会将原本的文件清空/覆盖。可以先用读(r)的方式打开,写到内存中,然后再用写(w)的方式打开。 1、替换文本中的taste 为 tasting Ye...