gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:48 27 4
gpt4 key购买 nike

我有如下的 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

最佳答案

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

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)

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

关于python - 使用 Python 按列名更新 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25723634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com