Skip to main content
 首页 » 编程设计

python之使用 Python 按列名更新 CSV 文件

2025年05月04日7soundcode

我有如下的 csv 文件:

product_name, product_id, category_id 
book, , 3 
shoe, 3, 1 
lemon, 2, 4 

我想通过使用 python 的 csv 库提供列名来更新每一行的 product_id。

举个例子,如果我通过了:

update_data = {"product_id": [1,2,3]} 

那么csv文件应该是:

product_name, product_id, category_id 
book, 1, 3 
shoe, 2, 1 
lemon, 3, 4 

请您参考如下方法:

您可以使用现有的 dict 和 iter 来按顺序获取项目,例如:

import csv 
 
update_data = {"product_id": [1,2,3]} 
# Convert the values of your dict to be directly iterable so we can `next` them 
to_update = {k: iter(v) for k, v in update_data.items()} 
 
with open('input.csv', 'rb') as fin, open('output.csv', 'wb') as fout: 
    # create in/out csv readers, skip intial space so it matches the update dict 
    # and write the header out 
    csvin = csv.DictReader(fin, skipinitialspace=True) 
    csvout = csv.DictWriter(fout, csvin.fieldnames) 
    csvout.writeheader() 
    for row in csvin: 
        # Update rows - if we have something left and it's in the update dictionary, 
        # use that value, otherwise we use the value that's already in the column. 
        row.update({k: next(to_update[k], row[k]) for k in row if k in to_update}) 
        csvout.writerow(row) 

现在 - 这假设每个新列值都转到行号,并且之后应该使用现有值。例如,您可以将该逻辑更改为仅在现有值为空白(或您希望的任何其他条件)时才使用新值。