我有一个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'对象不是迭代器
如何在第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,
答案 0 :(得分:2)
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)
答案 1 :(得分:0)
以下是您问题的解决方案, 首先,您读取的文件是2.csv,然后选择所需的行,直到保存行数据,然后在追加模式下打开另一个新的csv文件“desired.csv”并附加所需的行和列表
with open('2.csv', "rb") as fd:
reader = csv.reader(fd)
desired_rows = [row for idx, row in enumerate(reader) if idx < 9]
with open("desired.csv", "ab") as saved:
writer = csv.writer(saved)
writer.writerows(desired_rows)
writer.writerows(mylist)
希望这有帮助。