Python 将标准输出写入文件的更好方法

Python 将标准输出写入文件的更好方法,python,python-2.7,Python,Python 2.7,通常,当我将stdout写入文件时,我是这样做的 import sys sys.stdout = open(myfile, 'w') print "This is in a file." 现在,这个方法在我看来很难看,我到处听说有更好的方法。如果是这样的话,这个更好的方法是什么?您还可以利用打印实际上可以写入文件这一事实 with open("file.txt", "w") as f: print("Hello World!", file=fd) NB:这是Python3.x语法,因

通常,当我将
stdout
写入文件时,我是这样做的

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

现在,这个方法在我看来很难看,我到处听说有更好的方法。如果是这样的话,这个更好的方法是什么?

您还可以利用
打印
实际上可以写入文件这一事实

with open("file.txt", "w") as f:
    print("Hello World!", file=fd)
NB:这是Python3.x语法,因为
print
是Python3.x中的函数

但是,对于Python 2.x,您可以执行以下操作:

from __future__ import print_function
否则,也可以通过以下方式实现:

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

请参阅:来自Python 3.x文档。

使用

with open(myfile, 'w') as fh:
    fh.write("This is in a file.\n")


您可以像其他答案中所示那样执行,但是在每个语句中指定输出文件有点旧。因此,我理解只重定向
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."
请注意,您可以使用
作为
关键字来获取上一个
标准输出
,因此您仍然可以使用块在
内的屏幕上打印:

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"

很高兴在电视上见到你,总统先生。请参阅此相关/重复线程:
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."
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"