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

时间:2018-09-05 10:57:15

标签: 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_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包含1 2 3 4,而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

我要在这里实现的是脚本应该从DailyData中的HistoricData复制相同的数据

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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我建议您使用logging模块https://docs.python.org/2/howto/logging-cookbook.html

您可以创建两个追加程序(每个文件一个)和一种适合您需要的日志记录格式。

猴子修补sys.stdout是一种骇人听闻的方法,可用来实现对标准库中已包含的适当类的处理。

答案 1 :(得分:0)

如果我正确理解了这一点,则您正在尝试将一些数据写入文件(Dailydata.txt),将其复制到另一个文件(historicData.txt)上,然后在第二次迭代时,您希望{{1} }用新数据重写,并在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))
相关问题