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

yipeiwu_com4年前Python基础

方法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] 

以上这篇对python-3-print重定向输出的几种方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python中使用base64模块处理字符编码的教程

在Python中使用base64模块处理字符编码的教程

Base64是一种用64个字符来表示任意二进制数据的方法。 用记事本打开exe、jpg、pdf这些文件时,我们都会看到一大堆乱码,因为二进制文件包含很多无法显示和打印的字符,所以,如果要...

python reduce 函数使用详解

python reduce 函数使用详解

reduce() 函数在 python 2 是内置函数, 从python 3 开始移到了 functools 模块。 官方文档是这样介绍的 reduce(...) reduce(fu...

python安装pywin32clipboard的操作方法

要使用到剪贴板的方法,搜索到有两个包可以用,pyperclip,和pywin32clipboard,pyperclip在3.5版本中不能够import,可以手动下载安装,未查到原因;py...

python分割和拼接字符串

关于string的split 和 join 方法对导入os模块进行os.path.splie()/os.path.join() 貌似是处理机制不一样,但是功能上一样。1.string.s...

python3使用matplotlib绘制散点图

python3使用matplotlib绘制散点图

本文实例为大家分享了python3使用matplotlib绘制散点图,并标注图例,轴,供大家参考,具体内容如下 代码 from matplotlib import pyplot as...