使用Python按列名更新CSV文件
我的csv文件如下所示:使用Python按列名更新CSV文件,python,csv,Python,Csv,我的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 le
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
(假设您使用的是3.x)
Python在标准库中有一个CSV模块,可以帮助读取和修改CSV文件
使用它,我将找到您要查找的列的索引,并将其存储在您制作的词典中。一旦找到了,只需将列表项弹出到每一行中即可
import csv
update_data = {"product_id": [None, [1,2,3]]}
#I've nested the original list inside another so that we can hold the column index in the first position.
line_no = 0
#simple counter for the first step.
new_csv = []
#Holds the new rows for when we rewrite the file.
with open('test.csv', 'r') as csvfile:
filereader = csv.reader(csvfile)
for line in filereader:
if line_no == 0:
for key in update_data:
update_data[key][0] = line.index(key)
#This finds us the columns index and stores it for us.
else:
for key in update_data:
line[update_data[key][0]] = update_data[key][1].pop(0)
#using the column index we enter the new data into the correct place whilst removing it from the input list.
new_csv.append(line)
line_no +=1
with open('test.csv', 'w') as csvfile:
filewriter = csv.writer(csvfile)
for line in new_csv:
filewriter.writerow(line)
您可以使用现有的
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)
现在-这假设每个新列值都指向行号,然后使用现有值。例如,您可以将该逻辑更改为仅在现有值为空时使用新值(或您希望的任何其他条件) 这在Python中当然是可以做到的。到目前为止你试过什么?你困在哪里了?我试着用列名编一本字典。但我肯定不知道如何更新特定列上的值。我是python的新手。我只知道ruby。@Vimal列的长度总是等于行的数量吗?不。这将有所不同。而且列的数量也不是固定的。`……python新手。```-花点时间在文档中,它可能会给你一些想法。您可能还想尝试-是否可以在同一个文件上输出?@Vimal通常最好删除现有的一个文件,然后重新命名另一个文件-已经有很多答案详细说明了如何在Python中实现这一点-因此我在这里重新迭代它们没有多大意义…是的,这对我来说是有意义的。我试试看。谢谢