[英]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)輕松將單獨的appended(list)result1和result2寫入單獨的文件時,可以輕松完成此操作。 但是,我想在每次迭代中都寫入csv文件,這樣我就不會因為某種原因不得不中斷循環。
謝謝!
您可以在上下文管理器中放置兩個文件,並具有兩個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)
如果有多個項目,則上下文管理器的處理就像嵌套了多個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)
...
當前,您僅聲明了一個writer變量。 您將需要第二個writer變量。
fWriter = csv.write(f)
...
gWriter = csv.write(g)
...
fWriter.writerow(pa)
...
gWriter.writerow(pb)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.