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

时间:2016-05-03 22:26:19

标签: python csv for-loop contextmanager

我有

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)可以轻松地将单独的附加(list)result1和result2写入单独的文件时,可以轻松完成此操作。但是,我想在每次迭代中写入csv文件,所以如果由于某种原因我必须打破循环,我不会错过。

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以在上下文管理器中放置两个文件,并拥有两个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.73.5相同)。

  

如果有多个项目,则会处理上下文管理器,就像多个with语句嵌套一样:

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

相当于

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)
        ...

答案 1 :(得分:0)

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

fWriter = csv.write(f)

...

gWriter = csv.write(g)

...

fWriter.writerow(pa)

...

gWriter.writerow(pb)