假设我正在将stdout
写入文件,如下所示:
sys.stdout = open("file.txt", "w")
# print stuff here
这样做不起作用:
sys.stdout.close()
如何在向stdout
写入文件后关闭文件?
答案 0 :(得分:2)
我的问题是:“如何将sys.stdout
重定向到文件?”
import sys
# we need this to restore our sys.stdout later on
org_stdout = sys.stdout
# we open a file
f = open("test.txt", "w")
# we redirect standard out to the file
sys.stdout = f
# now everything that would normally go to stdout
# now will be written to "test.txt"
print "Hello world!\n"
# we have no output because our print statement is redirected to "test.txt"!
# now we redirect the original stdout to sys.stdout
# to make our program behave normal again
sys.stdout = org_stdout
# we close the file
f.close()
print "Now this prints to the screen again!"
# output "Now this prints to the screen again!"
# we check our file
with open("test.txt") as f:
print f.read()
# output: Hello World!
这是你问题的答案吗?
答案 1 :(得分:1)
你可以这样做:
import sys
class writer(object):
""" Writes to a file """
def __init__(self, file_name):
self.output_file = file_name
def write(self, something):
with open(self.output_file, "a") as f:
f.write(something)
if __name__ == "__main__":
stdout_to_file = writer("out.txt")
sys.stdout = stdout_to_file
print "noel rocks"
只有在您这样写文件时,该文件才会打开。
答案 2 :(得分:1)
如果要将所有print()重定向到文件,也可以执行此操作,这是一种快速的方法,我认为也是有用的,但它可能会产生其他影响。如果我错了,请纠正我。
import sys
stdoutold = sys.stdout
sys.stdout = fd = open('/path/to/file.txt','w')
# From here every print will be redirected to the file
sys.stdout = stdoutold
fd.close()
# From here every print will be redirected to console