0

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

### 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

4

2 回答 2

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.

无论如何,我同意阿什维尼的观点。当您真正应该使用不同的方法时,您似乎正在搜索黑客以获得某些东西。

于 2013-06-17T06:44:13.160 回答
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.
于 2013-06-16T19:44:57.800 回答