gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:36:58 27 4
gpt4 key购买 nike

我有

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 文件,这样我就不会因为某种原因不得不中断循环而错过。

谢谢!

最佳答案

您可以将两个文件放在一个上下文管理器中,并有两个 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 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)
...

关于python - 如何将for循环中的结果写入多个CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37015439/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com