【发布时间】:2014-11-27 20:00:13
【问题描述】:
我有这样的 csv 文件:
fio,username,otdel
Andrey,a.andrey,it
Vlad,v.vlad,support
Love,l.love,bill
Vasy,v.pupkin,main
我需要像这样混合它
User,fio2,username2,otdel2
a.andrey,Vlad,v.vlad,support
a.andrey,Love,l.love,bill
a.andrey,Vasy,v.pupkin,main
v.vlad,Andrey,a.andrey,it
v.vlad,Love,l.love,bill
v.vlad,Vasy,v.pupkin,main
.....
我做了这个代码:
import csv
def mixusr(filecsv):
csvfile = csv.DictReader(open(filecsv), delimiter=",")
outfile = csv.writer(open('pile.csv', 'w'), delimiter=',')
outfile.writerow(['User', 'fio2', 'username2', 'otdel2'])
for key in csvfile:
outfile.writerow([key['username'], key['fio'], key['username'], key['otdel']])
for xkey in csvfile:
outfile.writerow([key['username'], xkey['fio'], xkey['username'], xkey['otdel']])
mixusr('list.csv')
但它会停止迭代,输出是
User,fio2,username2,otdel2
v.vlad,Vlad,v.vlad,support
v.vlad,Andrey,a.andrey,it
v.vlad,Love,l.love,bill
v.vlad,Vasy,v.pupkin,main
我做错了什么。 当我这样做时
def mixusr(filecsv):
csvfile = csv.DictReader(open(filecsv), delimiter=",")
**csvfile2 = csv.DictReader(open(filecsv), delimiter=",")**
outfile = csv.writer(open('pile.csv', 'w'), delimiter=',')
outfile.writerow(['User', 'fio2', 'username2', 'otdel2'])
for key in csvfile:
outfile.writerow([key['username'], key['fio'], key['username'], key['otdel']])
for xkey in **csvfile2**:
outfile.writerow([key['username'], xkey['fio'], xkey['username'], xkey['otdel']])
我明白了:第二次迭代不起作用,我不知道有什么问题!!帮助
User,fio2,username2,otdel2
v.vlad,Vlad,v.vlad,support
v.vlad,Vlad,v.vlad,support
v.vlad,Andrey,a.andrey,it
v.vlad,Love,l.love,bill
v.vlad,Vasy,v.pupkin,main
a.andrey,Andrey,a.andrey,it
l.love,Love,l.love,bill
v.pupkin,Vasy,v.pupkin,main
【问题讨论】:
-
我不经常使用
csv模块,但我有一种感觉,你只能遍历一个csv文件一次。尝试第二次迭代它会给你零行。 -
同意,问题是在两个循环中使用相同的读取器迭代器。内循环第一次迭代后,迭代器耗尽,外循环结束。参见例如here 类似问题。
标签: python csv dictionary iteration