python在for循环中使用多个子进程写入同一文件

时间:2017-04-25 15:20:50

标签: python file file-io fwrite

我正在尝试将几个子进程python程序的输出写入同一个文件。主python程序如下所示:

forums = ["f20","e70","x3","e89","series7","m5","f10","series6","z4e85","i3i8","f22","f80","f15","f48","f87"]

for f in forums:
        command = "python 01-measurevariation.py "+ f+"-commoncrawl-timestamp.csv-excludeunif"
        print command
        exit_status = subprocess.call(command, shell=True)

子进程python程序01-measurevariation.py就在这里(仅显示相关代码):

    input_file= str(sys.argv[1])
    output_file = "tsvariations.csv"
    ...
    with open(input_file) as to_read:
        with open(output_file, "wb") as tmp_file:
            reader = csv.reader(to_read, delimiter = ",")
            writer = csv.writer(tmp_file)
            ....
            writer.writerow (["variance of "+sys.argv[1]+" is "+"%.2f" % numpy.var(difflist)+ " hours"])
            writer.writerow (["std of "+sys.argv[1]+" is "+ "%.2f" % numpy.std(difflist) +" hours"])

但是,输出文件“tsvariations.csv”只包含2行,这是主python程序中for循环中最后一个子进程的输出。

我希望tsvariations.csv包含所有子进程输出,它应该总共有30行。 (“论坛”列表中的15个条目中的每一个都有2行)。我怎样才能做到这一点?谢谢。

1 个答案:

答案 0 :(得分:0)

  

已在评论中解决:
   以追加模式打开文件。 - 昨天的光谱