正如我搜索过的一样,实际上同时阅读和编辑似乎并不那么容易,我还没有设法实现它.但是最让我困惑的是如何在csv的“ n”行中添加元素,例如,我想在csv的第2行中添加一行.
mycsv.csv
name,last name
yeison,smith
lola,boa
elmo,spitia
anderson,exneider
juan,ortega
我的代码:
with open("mycsv.csv","r") as rfh:
r = csv.DictReader(rfh)
for idx,row in enumerate(r): #nothing happens
print(r)
with open("mycsv.csv","a") as wfh:
if(idx==2):
#append element "german,ezequiel"
最佳答案
阅读所有行然后编写应该可以:
with open('mycsv.csv','r') as f:
lines = f.readlines()
lines.insert(2,'german,ezequiel')
with open('mycsv.csv','w') as f:
f.write(''.join(lines))