将stdout写入文件的更好方法

时间:2014-07-17 03:02:04

标签: python python-2.7

通常,当我将stdout写入文件时,我会这样做。

import sys
sys.stdout = open(myfile, 'w')
print "This is in a file."

现在,这种方法对我来说看起来很难看,而且我已经在这里和那里听说有更好的方法。如果是这样,这个更好的方法是什么?

3 个答案:

答案 0 :(得分:4)

您还可以利用print实际可以写入文件的事实。

with open("file.txt", "w") as f:
    print("Hello World!", file=fd)

NB:这是Python 3.x语法,因为print是Python 3.x中的一个函数。

对于Python 2.x,您可以这样做:

from __future__ import print_function

否则可以通过以下方式实现:

with open("file.txt", "w") as fd:
    print >> fd, "Hello World!"

请参阅:Python 3.x文档中的print()

答案 1 :(得分:3)

使用

直接打印到文件
with open(myfile, 'w') as fh:
    fh.write("This is in a file.\n")

with open(myfile, 'w') as fh:
    print >>fh, "This is in a file."

from __future__ import print_function
with open(myfile, 'w') as fh:
    print("This is in a file.", file=fh)

答案 2 :(得分:2)

您可以按照其他答案中的说明执行此操作,但它会在每个语句中指定输出文件。所以我理解只需重定向sys.stdout的冲动。但是,是的,你提出这样做​​的方式并不像它那样优雅。添加适当的错误处理将使其更加丑陋。幸运的是,您可以创建一个方便的上下文管理器来解决这些问题:

import sys, contextlib

@contextlib.contextmanager
def writing(filename, mode="w"):
    with open(filename, mode) as outfile:
        prev_stdout, sys.stdout = sys.stdout, outfile
        yield prev_stdout
        sys.stdout = prev_stdout

用法:

with writing("filename.txt"):
     print "This is going to the file"
     print "In fact everything inside the with block is going to the file"
print "This is going to the console."

请注意,您可以使用as关键字获取之前的stdout,这样您仍然可以打印到with块内的屏幕:

with writing("filename.txt") as stdout:
     print "This is going to the file"
     print >> stdout, "This is going to the screen"
     print "This is going to the file again"