Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update CSV file by column name using Python

Tags:

python

csv

I have the csv file as follows:

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

I would like to update product_id of each row by providing the column name using python's csv library.

So for an example if I pass:

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

then the csv file should be:

product_name, product_id, category_id
book, 1, 3
shoe, 2, 1
lemon, 3, 4
like image 655
Vimalraj Selvam Avatar asked Dec 04 '25 01:12

Vimalraj Selvam


1 Answers

You can use your existing dict and iter to take items in order, eg:

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)

Now - this assumes that each new column value goes to the row number and that the existing values should be used after that. You could change that logic to only use new values when the existing value is blank for instance (or whatever other criteria you wish).

like image 142
Jon Clements Avatar answered Dec 06 '25 15:12

Jon Clements