使用Python2.7打开文件a,将其转换为一个字典,第0行为键,第3行为值。然后打开文件b,为第0行中的匹配ID号追加匹配的其他列。然后转换回一个列表并合并两个CSV
结尾处添加页眉并另存为“输出.csv“。”
我所期待的是:
文件a:
1234, 14/12/2,123.4,
5618, 13/1/12,23.4,
9143, 15/2/14,222.4,
文件b:
^{pr2}$(输出)梦想:
payment date, payment amount, other id, other other id, payment status, payment type
14/12/2,123.4,1234,abc,cda, Received, Recurring
13/1/12,23.4,9143,nda, bad, Received, Recurring
15/2/14,222.4,5618, ede, fpc,Received, Recurring
(实际)输出:
ID, payment date, payment amount, other id, other other id, payment status, payment type
1234, 14/12/2,123.4,1234,abc,cda, Received, Recurring
5618, 13/1/12,23.4,9143,nda, bad, Received, Recurring
9143, 15/2/14,222.4,5618, ede, fpc,Received, Recurring
代码:
import csv
#create a dict from first csv, with clearing solution id as key
with open("DDS.csv", "rb") as f:
first = {rows[0]: rows[3:] for rows in list(csv.reader(f))}
# compare second csv, append rank, add received recurring columns
with open("report.csv", "rb") as f:
for row in csv.reader(f):
if row and row[0] in first: # row[0] = clearing solution id
first[row[0]].append(row[1]) # row[1] = rank
first[row[0]].append(row[2])
first[row[0]].append('Received')
first[row[0]].append('Recurring')
# convert dict back to list
merged = [(k,) + tuple(v) for k, v in first.items()]
# write list to output csv
with open('output.csv', "w") as f:
writer = csv.DictWriter(f, fieldnames =['ID', 'Payment Date', 'Payment Amount', 'Other ID','other other ID', 'Payment Status', 'Payment Type'])
writer.writeheader()
csv.writer(f).writerows(merged)
奖励积分: 如何从输出CSV中删除第一列?在
谢谢
您可以删除第一个,只需不要将
(k,)
添加到元组并删除 字段名中的“ID”。不需要创建另一个编写器来编写csv.writer(f).writerows(merged)
行?公司名称:我建议使用经典的python字符串操作,而不是csv模块。在
例如,使用
rows.replace(' ','').split(,)[0]
代替rows[0]
应该可以解决空间问题。在相关问题 更多 >
编程相关推荐