分享

python 的重定向输出到一个文件

 星光闪亮图书馆 2018-03-28
f=open('a.txt','w')
import sys
old=sys.stdout #将当前系统输出储存到一个临时变量中
sys.stdout=f  #输出重定向到文件
print('Hello world!',file=f) #测试一个打印输出
sys.stdout=old #还原原系统输出
f.close()
f1=open('a.txt','r') 
print(f1.read())
f1.close()

注意sys库的使用,文件位置默认位于你运行的源代码所在的位置。
同样可以自行编写一个类,这个类只要有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]

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多