在python中重定向两个不同文件中的输出

在python中重定向两个不同文件中的输出,python,python-2.7,Python,Python 2.7,我将脚本的输出记录在两个不同的文件中,Dailydata.txt和historicData.txt。 我希望我只需要stdout在下面两个不同的文件中 sys.stdout = open('historicData.txt', 'a+') sys.stdout = open('Dailydata.txt', 'r+') 但是,它只将输出定向到一个文件 因此,我首先将输出重定向到DailyData.txt,然后将其写入HistoricData.txt with open(file

我将脚本的输出记录在两个不同的文件中,Dailydata.txt和historicData.txt。 我希望我只需要
stdout
在下面两个不同的文件中

sys.stdout = open('historicData.txt', 'a+')
sys.stdout = open('Dailydata.txt', 'r+')
但是,它只将输出定向到一个文件

因此,我首先将输出重定向到
DailyData.txt
,然后将其写入
HistoricData.txt

        with open(file_path + 'HistoricDaily.txt', 'r') as fread, open(file_path + 'FidelityHistoric.txt', 'a+') as fwrite:
            fread_lines = fread.readlines()
            for i in fread_lines:
                fwrite.write(i)
这里发生的是,每次我运行脚本时,它都会写入当前的运行编号 说
HistoricData.txt
包含
1234
DailyData.txt
包含
5
。 当我运行脚本时,
DailyData.txt
将包含
6
,它不是复制
6
,而是复制
5
。如果我再次运行它,它将复制
6
,而不是
7

我的剧本是这样的

class MyClass:

    stdout = open('historicData.txt', 'a+')
try:
# my code Selenium stuff


except:
# my code

finally:
     # copy data to HistoricData here
我在这里试图实现的是脚本应该从
HistoricData
中的
DailyData
复制相同的数据

同时重定向2个不同文件中的数据


任何帮助都将不胜感激。

我鼓励您使用
日志记录
模块

您可以创建两个appender(每个文件一个)和适合您需要的日志格式


Monkey patching
sys.stdout
是一种黑客方法,可以通过标准库中已经包含的适当类来实现您的功能。

如果我理解正确,您正在尝试将一些数据写入一个文件(
Dailydata.txt
),请将其复制到另一个文件(
historicData.txt
)然后,在第二次迭代中,您希望用新数据重写
Dailydata.txt
,并在
historicData.txt
的和处添加新数据

您可以尝试以下方法:

with open('Dailydata.txt', 'rb') as r:
    with open('historicData.txt', 'ab') as w:
        lines = r.readlines()
        for line in lines:
            w.write(str(line))
相反,如果要在两个文件中同时写入相同的数据,只需显式执行以下操作:

def my_data_generator():
   #do stuff

def my_writer():
   daily = open('Dailydata.txt', 'w')
   historic = open('historicData.txt', 'ab')
   data = my_data_generator()
   daily.write(data)
   historic.write(data)

谢谢你的回答。我想要的是将数据重定向到两个不同的文件中。我不能同时在两个不同的文件中输入数据。因此,我要做的是,首先重定向
DailyData
中的数据,然后将其写入
HistoricData
。现在事情变得棘手了。假设我第一次运行脚本并在
DailyData
中输出了1,但我的写代码(如上所述)没有将1复制到
HistoricData
。当我第二次运行脚本时,它在
DailyData
中写入
2
,在
HistoricData
中写入
1
。如果我第三次运行它,它将在DD中复制3,在HD中复制2,以此类推。HD shld hv与DDOk的数据相同,我编辑了我的答案,而不是将数据直接保存在文件中,您应该将其存储在变量中,然后将数据写入两个文件中。