gpt4 book ai didi

python - CSV writerows 在一些行之后

转载 作者:行者123 更新时间:2023-11-28 17:13:03 25 4
gpt4 key购买 nike

我有一个 CSV,比如 2.csv,在此处发布示例:

,ANPIS,,,,,,,
,AGENTIA JUDETEANA PENTRU PLATI SI INSPECTIE SOCIALA TIMIS,,,,,,,
,,,,,,,,
,Macheta Comparativa CREDITORI - numai pentru Beneficiile a caror Evidenta se tine si in Contabilitate si in aplicatia SAFIR,,,,,,,
,Situatie ANALITICA - NOMINAL la 30.06.2017,,,,,,,
,8. INDEMNIZATIE ART. 31 SI ART. 32 OUG 111/2010,,,,,,,
,Nr. Benef,Nume Prenume,CNP,Data Constituirii,Suma Contabilitate,Suma SAFIR,Differenta Suma,Explicatii daca exista diferente
,1,2,3,4,5,6,7=5-6,8
,1,IONELA,2820,Mai/2017,3579,3579,0,
,2,GHEORGHE,18609,Februarie/2017,185,185,0,
,3,GHEORGHE,186091,Martie/2017,185,185,0,
,4,GHEORGHE,18609,Aprilie/2017,185,185,0,

我想使用 python 3 覆盖它的列表列表 从第 9 行开始 并保持前 8 行现在的状态,我读了 next()可以跳过标题,我这样尝试:

import csv
with open("data//2.csv", "w") as f:
writer = csv.writer(f)
header = next(writer)
writer.writerows(mylist)

但这会产生:

TypeError: '_csv.writer' object is not an iterator

如何在第 8 行之后开始编写 mylist(在我的例子中)?感谢您的宝贵时间!

编辑:mylist 看起来像这样:

mylist= [['AUGUSTIN', 14111, 'Mar 2016', 0, 600], ['AUGUSTIN', 1451, 'Feb 2015', 0, 600], ['IOAN', 1480, 'Aug 2014, Sept 2014, Oct 2014', 0, 291]]

写入后我的输出将如下所示:

,ANPIS,,,,,,,
,AGENTIA JUDETEANA PENTRU PLATI SI INSPECTIE SOCIALA TIMIS,,,,,,,
,,,,,,,,
,Macheta Comparativa CREDITORI - numai pentru Beneficiile a caror Evidenta se tine si in Contabilitate si in aplicatia SAFIR,,,,,,,
,Situatie ANALITICA - NOMINAL la 30.06.2017,,,,,,,
,8. INDEMNIZATIE ART. 31 SI ART. 32 OUG 111/2010,,,,,,,
,Nr. Benef,Nume Prenume,CNP,Data Constituirii,Suma Contabilitate,Suma SAFIR,Differenta Suma,Explicatii daca exista diferente
,1,2,3,4,5,6,7=5-6,8
,AUGUSTIN, 14111, Mar 2016, 0, 600,
,AUGUSTIN, 1451, Feb 2015, 0, 600,
,IOAN, 1480, Aug 2014, Sept 2014, Oct 2014, 0, 291,

最佳答案

csv 文件不是可读写的。它们只是用迭代器映射的普通文本文件,但仅在使用 reader 时有效,因此 next 仅在读取时有效。

所以你必须读取前 8 行,存储它们,然后这次在输出中打开另一个文件(或再次打开那个文件),并存储 8 个标题行,然后是你的新输出。

此代码执行我刚刚描述的操作:

import csv
with open("input.csv", "r") as f:
reader = csv.reader(f)
start_of_list = [next(reader) for _ in range(8)]

mylist= [['AUGUSTIN', 14111, 'Mar 2016', 0, 600], ['AUGUSTIN', 1451, 'Feb 2015', 0, 600], ['IOAN', 1480, 'Aug 2014, Sept 2014, Oct 2014', 0, 291]]

with open("output.csv","w",newline="") as f:
writer = csv.writer(f)
writer.writerows(start_of_list)
writer.writerows(mylist)

关于python - CSV writerows 在一些行之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117964/

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