关闭一个正在写入stdout的文件
假设我正在把 stdout
(标准输出)写入一个文件,像这样:
sys.stdout = open("file.txt", "w")
# print stuff here
这样做是不行的:
sys.stdout.close()
我该怎么做才能在把 stdout
写入文件后关闭这个文件呢?
3 个回答
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"
这个文件只有在你像这样写入内容的时候才会被打开。
3
如果你想把所有的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
3
我理解你的问题是:“我怎么把 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!
这个回答对你的问题有帮助吗?