将CSV文件与选择列合并

时间:2015-12-19 03:34:44

标签: python csv

Python新手,试图弄清楚如何基于单个列(item.id)合并多个CSV文件,但我还想从每个文件中选择一个子集以包含在最终合并中。

每个CSV都有100列,只需要选定的列。

我有下面写的代码可以使用,但我真的需要一个CSV输出而不是创建几个文件。我有一个字段的字典,因为输出必须具有那些重命名的值。

import csv
from collections import OrderedDict

def processFile(source,fields):
    src = ('C:/MyDirectory/{FILENAME}_original.csv').format(FILENAME=source)
    dst = ('C:/MyDirectory/{FILENAME}_clean.csv').format(FILENAME=source)

    s = open(src, newline="")
    reader = csv.DictReader(s, delimiter=",",quotechar='"')

    t = open(dst,"w",newline="")
    writer = csv.writer(t,delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)

    headers = list(v for(k,v) in fields.items())
    writer.writerow(headers)

    next(reader) #Need to skip the 2nd row in every file - it has double headers

    for row in reader:
        content = list(row[k] for(k,v) in fields.items())
        writer.writerow(content)


fieldsFI1 = OrderedDict([
    ('item.id','ItemId'),
    ('att1','Attribute1'),
    ('att2','Attribute2'),
])

fieldsFI2 = OrderedDict([
    ('item.id','ItemId'),
    ('att3','Attribute3'),
    ('att4','Attribute4'),
])

processFile(FI1,fieldsFI1)
processFile(FI2,fieldsFI2)

1 个答案:

答案 0 :(得分:1)

这里有一些不太合适的事情。首先,当你完成它们时,你永远不会关闭你的文件 - 这是一个很大的禁忌。您可以使用with上下文管理器轻松解决此问题。其次,我会说处理所有数据并且然后写入新的csv要容易得多。我已经做了类似的事情,我将逻辑分为三部分:1)读取文件,2)按ID组合列表,3)编写新文件。

import csv
from collections import OrderedDict

def readFile(source,fields):
    src = ('C:/MyDirectory/{FILENAME}_original.csv').format(FILENAME=source)
    rows = list()

    with open(src, newline="") as s:
        reader = csv.DictReader(s, delimiter=",",quotechar='"')
        next(reader) #Need to skip the 2nd row in every file - it has double headers

        for row in reader:
            content = { v: row[k] for (k,v) in fields.items() } #dict comprehension
            rows.append(content)

    return rows

def writeFile(dest, fields, content):
    src = ('C:/MyDirectory/{FILENAME}_original.csv').format(FILENAME=dest)
    with open(dest,"w",newline="") as t:
        fieldnames = list(v for k,v in fields.items())
        writer = csv.DictWriter(t, fieldnames=fieldnames, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writer.writeheader()
        for c in content:
            c_dict = {v: c.get(v) for(k,v) in fields.items()
            writer.writerow(c_dict)


FI1 = "file_one"
FI2 = "file_two"
dest = "dest_file"

fieldsFI1 = OrderedDict([
    ('item.id','ItemId'),
    ('att1','Attribute1'),
    ('att2','Attribute2'),
])

fieldsFI2 = OrderedDict([
    ('item.id','ItemId'),
    ('att3','Attribute3'),
    ('att4','Attribute4'),
])

all_fields = fieldsFI1.copy()
all_fields.update(fieldsFI2)

list1 = readFile(FI1,fieldsFI1)
list2 = readFile(FI2,fieldsFI2)

merged = {}
for elem in list1 + list2:
    if elem['ItemId'] in merged:
        merged[elem['ItemId']].update(elem)
    else:
        merged[elem['ItemId']] = elem
content = [ v for (k, v) in merged.items() ]

writeFile(dest, all_fields, content)

这里复杂的部分是合并。 merged最终成为一个字典,其中键是项ID,每个ID的值也是一个字典,其键是文件中的字段。如果项目ID还没有条目,则创建一个条目,但如果条目ID,则创建该条目的值,并使用新字典中的条目更新该条目。