如何将for循环中的结果写入多个CSV文件

how to write results in a for loop to multiple CSV files

我有

with open ('~/abc.csv', 'w') as f:
    write1 = csv.write(f)
    write1.writerow(['header1', 'header2', 'header3', 'header4'])

with open ('~/def.csv', 'w') as g:
    write2 = csv.write(g)
    write2.writerow(['header1', 'header2', 'header3', 'header4', 'header5', 'header6'])

for iteration in a_list:
    perform calculations
    result1 = ([h1, h2, h3, h4],[l1, l2, l3, l4],[m1, m2, m3, m4], ...,[])
    for pa in result1:
        write1.writerow(pa)

    def fun(result1):
        result2 = ([n1, n2, n3, n4, n5, n6],[p1, p2, p3, p4, p5, p6], [], ...[])
        for pb in result2:
             write2.writerow(pb)

需要两个 csv 文件作为

'header1', 'header2', 'header3', 'header4'
h1, h2, h3, h4
l1, l2, l3, l4
m1, m2, m3, m4
      :

'header1', 'header2', 'header3', 'header4', 'header5', 'header6'
n1, n2, n3, n4, n5, n6
p1, p2, p3, p4, p5, p6

当所有迭代都完成时,这可以很容易地完成,并且可以使用 writer.writerows(pa) 将单独的附加(列表)result1 和 result2 轻松写入单独的文件。但是,我想在每次迭代中都写入 csv 文件,这样我就不会因为某种原因不得不中断循环而错过。

谢谢!

目前,您只声明了一个编写器变量。您将需要第二个编写器变量。

fWriter = csv.write(f)

...

gWriter = csv.write(g)

...

fWriter.writerow(pa)

...

gWriter.writerow(pb)

您可以在一个上下文管理器中放置两个文件并拥有两个 csv.writer 对象(自 Python 2.7 起):

with open ('~/abc.csv', 'w') as f, open ('~/def.csv', 'w') as g:
    writer1 = csv.writer(f)
    writer2 = csv.writer(g)

    writer1.writerow(['header1', 'header2', 'header3', 'header4'])    
    writer2.writerow(['header1', 'header2', 'header3', 'header4', 'header5', 'header6'])

    for iteration in a_list:
        # perform calculations
        for pa in result1:
            writer1.writerow(pa)
        for pb in result2:
            writer2.writerow(pb)

来自文档(与 Python 2.7 up to 3.5 相同)。

With more than one item, the context managers are processed as if multiple with statements were nested:

with A() as a, B() as b:
    suite

is equivalent to

with A() as a:
    with B() as b:
        suite

这表明另一种方法是让嵌套更深一层。

with open ('~/abc.csv', 'w') as f:
    with open ('~/def.csv', 'w') as g:
        writer1 = csv.writer(f)
        writer2 = csv.writer(g)
        ...