对python-3-print重定向输出的几种方法总结
方法1:
importsys
f=open('test.txt','a+')
a='123'
b='456'
print>>f,a,b
f.close()
方法2:
importsys
f=open('a.txt','w')
old=sys.stdout#将当前系统输出储存到临时变量
sys.stdout=f#输出重定向到文件
print'HelloWorld!'#测试一个打印输出
sys.stdout=old#还原系统输出
f.close()
printopen('a.txt','r')#错误的方法,仅用于查看输出,了解python
printopen('a.txt','r').read()
importsys
year=1
years=15
bj=10000
rate=0.05
f=open('total.txt','w+')
whileyear>f,"第%d年,本息合计%0.2f"%(year,bj)
year+=1
方法3:
自行编写一个类,这个类只要有write函数,以模拟file类型就可以将系统输出重定向到其上。
classFakeOut: def__init__(self): self.str='' self.n=0 defwrite(self,s): self.str+="Out:[%s]%s\n"%(self.n,s) self.n+=1 defshow(self):#显示函数,非必须 printself.str defclear(self):#清空函数,非必须 self.str='' self.n=0 f=FakeOut() importsys old=sys.stdout sys.stdout=f print'Helloweird.' print'Helloweirdtoo.' sys.stdout=old f.show() #输出: #Out:[0]Helloweird. #Out:[1] #Out:[2]Helloweirdtoo. #Out:[3]
以上这篇对python-3-print重定向输出的几种方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。