对python-3-print重定向输出的几种方法总结

作者:挣点生活费的小落落 时间:2023-10-21 19:38:58 

方法1:


import sys

f=open('test.txt','a+')
a='123'
b='456'
print >> f,a,b
f.close()

方法2:


import sys

f=open('a.txt','w')
old=sys.stdout #将当前系统输出储存到临时变量
sys.stdout=f #输出重定向到文件
print 'Hello World!' #测试一个打印输出
sys.stdout=old  #还原系统输出
f.close()
print open('a.txt','r') # 错误的方法,仅用于查看输出,了解python
print open('a.txt','r').read()

import sys
year=1
years=15
bj=10000
rate=0.05
f=open('total.txt','w+')
while year < years:
  bj=bj*(1+rate)
  print >> f,"第%d年,本息合计%0.2f" % (year,bj)
  year+=1

方法3:

自行编写一个类,这个类只要有write函数,以模拟file类型就可以将系统输出重定向到其上。


class FakeOut:
def __init__(self):
 self.str=''
 self.n=0
def write(self,s):
 self.str+="Out:[%s] %s\n"%(self.n,s)
 self.n+=1
def show(self): #显示函数,非必须
 print self.str
def clear(self): #清空函数,非必须
 self.str=''
 self.n=0
f=FakeOut()
import sys
old=sys.stdout
sys.stdout=f
print 'Hello weird.'
print 'Hello weird too.'
sys.stdout=old
f.show()
# 输出:
# Out:[0] Hello weird.
# Out:[1]

# Out:[2] Hello weird too.
# Out:[3]

来源:https://blog.csdn.net/qq_35528593/article/details/74453104

标签:python3,print,重定向
0
投稿

猜你喜欢

  • python调用系统ffmpeg实现视频截图、http发送

    2021-05-20 13:18:53
  • python logging通过json文件配置的步骤

    2022-06-04 22:30:19
  • Python 迭代器Iterator详情

    2021-10-12 07:01:42
  • 原生JS实现旋转木马式图片轮播插件

    2024-04-17 09:45:08
  • c#连接mysql数据库的方法

    2024-01-23 02:52:32
  • 网页栅格系统研究(3):粒度问题

    2008-10-28 19:46:00
  • Linux上通过binlog文件恢复mysql数据库详细步骤

    2024-01-27 17:56:01
  • Python中内建函数的简单用法说明

    2021-09-01 08:19:58
  • 基于Python的ModbusTCP客户端实现详解

    2022-02-03 10:54:25
  • Golang的继承模拟实例

    2024-05-08 10:23:14
  • Python+Pygame实现之走四棋儿游戏的实现

    2023-08-29 21:34:55
  • 用javascript对一个json数组深度赋值示例

    2024-04-23 09:22:54
  • Python爬虫JSON及JSONPath运行原理详解

    2023-02-21 17:59:48
  • js 可选链操作符的使用

    2023-08-18 16:04:57
  • 如何查看MySQL连接的root密码

    2024-01-25 08:47:43
  • Python NumPy灰度图像的压缩原理讲解

    2021-02-16 02:46:33
  • 基于Python实现2种反转链表方法代码实例

    2021-11-27 21:19:02
  • Python去除字符串前后空格的几种方法

    2021-12-22 02:10:02
  • 详解python使用canvas实现移动并绑定键盘

    2022-08-18 01:02:52
  • NumPy.npy与pandas DataFrame的实例讲解

    2022-11-18 07:39:00
  • asp之家 网络编程 m.aspxhome.com