我想插入相对于其列从2nd.csv到1st.csv的某一行。
这是我的文件
1st.csv
store_name_id seller_name date_hired age
100 jed 2014/0707 33
200 ej 2014/0708 33
200 charm 2014/0709 11
111 teahaa 2014/0710 22
111 luis 2014/0711 12
200 jess 2014/0712 66
2nd.csv
ID Store_Name Store_description contacts
100 new store newly build store 1313134
200 young store the owner is young 1111111
111 pretty store the owner is pretty cool 1231331
这是我的python代码:
#!/usr/bin/python
import csv
d = {}
with open("1st.csv", 'rb') as f:
for row in csv.reader(f, delimiter=','):
d[row[0]] = row
with open("2nd.csv", 'rb') as f:
for row in csv.reader(f, delimiter=','):
old_row = d.setdefault(row[0], [row[0]])
old_row[4:] = row[1:]
with open("output.csv", "w") as f:
csv.writer(f, delimiter='\t').writerows(d.values())
但输出是:
一些像这样(不实际):
100 jed 2014/0707 33
100 new store newly build store 1313134
200 ej 2014/0708 33
200 young store the owner is young 1111111
200 charm 2014/0709 11
111 teahaa 2014/0710 22
111 luis 2014/0711 12
111 pretty store the owner is pretty cool 1231331
他们合并是,但我的期望和想要的输出必须像这样
store_name_id seller_name date_hired age Store_name Store_description contacts
100 jed 2014/0707 33 new store newly build store 1313134
200 ej 2014/0708 33 young store the owner is young 1111111
200 charm 2014/0709 11 young store the owner is young 1111111
111 teahaa 2014/0710 22 pretty store the owner is pretty cool 1231331
111 luis 2014/0711 12 pretty store the owner is pretty cool 1231331
200 jess 2014/0712 66 young store the owner is young 1111111
我还是新手,正在学习这种语言。请帮忙。
像这样的输出
store_name_id seller_name date_hired age Store_name Store_description contacts
100 jed 2014/0707 33 new store newly build store 1313134
200 ej 2014/0708 33 young store the owner is young 1111111
111 teahaa 2014/0710 22 pretty store the owner is pretty cool 1231331
它只得到一个数据,其余的store_name_id都消失了。
最佳答案
我相信您遇到的问题是csv输出完全不正常。那是因为字典没有任何顺序感,所以d.values()
的结果在大多数情况下会处于任意顺序。
因此,与其使用字典,不如使用列表来存储,甚至可以使用字典来指向该行的索引。
根据评论,您似乎也正在以错误的顺序读取文件,您需要首先读取b,制作其存储列表,然后读取a并创建输出列表。
范例-
import csv
d = {}
lst = []
with open("b.csv", 'r') as f:
reader = csv.reader(f, delimiter=',')
header = next(reader)[1:]
for i, row in enumerate(reader):
d[row[0]] = i
lst.append(row)
newlst = []
with open("a.csv", 'r') as f:
reader = csv.reader(f, delimiter=',')
head = next(reader)
head.extend(header)
newlst.append(head)
for row in reader:
idx = d.get(row[0], -1)
if idx != -1:
old_row = lst[idx]
row.extend(old_row[1:])
else:
row = row + ["","","",""]
newlst.append(row)
with open("output.csv", "w") as f:
csv.writer(f, delimiter='\t').writerows(newlst)