如何使用stdout将打印消息的内容记录到两个文件中

时间:2013-06-16 19:13:34

标签: python logging python-2.7 stdout output

寻找一些帮助记录/保存打印到两个文件位置的帮助,如下所示,有没有人知道这样做的方法?

### Create output file/open it for editing
output_file = open('FILE.txt','w')
output_file1 = open('FILE_APPENDING.txt','a')

## Create a backup of current setting
old_stdout = sys.stdout

sys.stdout = output_file
sys.stdout = output_file1

print "stuff here"
## loop here printing stuff

## Revert python to show prints as normal
sys.stdout=old_stdout

## Close the file we are writing too
output_file.close()
output_file1.close()

提前致谢 - Hyflex

2 个答案:

答案 0 :(得分:3)

您可以将sys.stdout重新分配给写入多个文件的某个类:

class MultiWrite(object):
    def __init__(self, *files):
        self.files = files
    def write(self, text):
        for file in self.files:
            file.write(text)
    def close(self):
        for file in self.files:
            file.close()

import sys

# no need to save stdout. There's already a copy in sys.__stdout__.
sys.stdout = MultiWrite(open('file-1', 'w'), open('file-2', 'w'))
print("Hello, World!")

sys.stdout.close()

sys.stdout = sys.__stdout__  #reassign old stdout.

无论如何,我同意Ashwini。当你真正使用不同的方法时,似乎你正在寻找一种能够获得某些东西的东西。

答案 1 :(得分:2)

只需使用file.write

with open('FILE.txt','w')  as output_file:
    #do something here
    output_file.write(somedata) # add '\n' for a new line

with open('FILE_APPENDING.txt','a')  as output_file1:
    #do something here
    output_file1.write(somedata) 

file.write上的帮助:

>>> print file.write.__doc__
write(str) -> None.  Write string str to file.

Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.