Python导入STD输出到一个新文件



我有一组打印stmts,当我在python shell中运行时打印,但我想将它们保存在一个文件中,而不改变输出顺序,因为它在shell输出中。

我有一部分文件有打印stmts,我必须把它们保存到一个新文件:

with open('myfile') as f:
            print best1
            print best2   
            s1 = ('best1'+'best2')
            print s1
with open('newfile') as f: #<-dont know how to display in newfile for above print stmts

如何在不改变输出顺序的情况下将它们保存到新文件中?

"print"语句默认写入标准输出。但是,您仍然可以使用它来写入其他目标。

旧风格:

with open("/tmp/testme.txt", "w") as fo:
    print >>fo, "some text."
新风格:

from __future__ import print_function
with open("/tmp/testme.txt", "w") as fo:
    print("some text.", file=fo)

后者是您将在Python 3中使用的(或2中使用__future__导入,您在3中省略了它)。

相关内容

最新更新