具有意外双空间Python的CSV文件

时间:2015-04-14 00:23:37

标签: python csv

使用Python 2.7打开文件a将其转换为字典,其中第0行为键,第3行为值。然后打开文件b,获取第0行中匹配的ID号,以附加匹配的其他列。然后转换回列表并合并两个CSV。

最后添加标题并保存为“output.csv。”

我所期待的例子:

档案a:

1234, 14/12/2,123.4,
5618, 13/1/12,23.4,
9143, 15/2/14,222.4,

文件b:

1234,abc,cda
9143,nda, bad 
5618, ede, fpc

(梦)输出:

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中删除第一列?

由于

2 个答案:

答案 0 :(得分:0)

你可以摆脱第一个只是不要将(k,)添加到你的元组并删除 来自字段名称的“ID”。您不需要创建另一个编写器来编写行csv.writer(f).writerows(merged)?:

merged = [tuple(v) for k, v in first.items()]
with open('output.csv', "w") as f:
    writer = csv.DictWriter(f, fieldnames =['Payment Date', 'Payment Amount', 'Other ID','other other ID', 'Payment Status', 'Payment Type'])
    writer.writeheader()
    writer.writerows(merged)

答案 1 :(得分:-1)

我建议使用经典的python字符串操作代替csv模块。

例如,使用rows.replace(' ','').split(,)[0]代替rows[0]可以解决空间问题。