想知道如何在csv中为现有数字添加数字
清单?
例如,
如果我的csv列表看起来像:
你好,2,11
再见,5,6
称呼,7,17
..................
如果我的清单看起来像:
[['hello','5','1'],['goodbye','12','8'],
['salutations','14,'9'] ...................]
我有写文件的基本纲要
with open("namesList.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(ranking)
似乎无法弄清楚如何添加数字
非常感谢
最终清单理想情况如下:
你好,7,12
再见,17,14
致敬,21,26
答案 0 :(得分:0)
您可以使用Pandas库在python中编写csv文件
dataframe = Dataframe.from_records(your_list)
dataframe.to_csv('directory/yourfile.csv')
答案 1 :(得分:0)
l=[['hello','5','1'], ['goodbye', '12', '8'], ['salutations', '14','9']]
y=[]
# Read the csv, match first element in csv with that in list
# Creates a new list y, with the updated values
# While updating the sum, had to convert to integer as the numbers were in string format
with open("namesList.csv", "r") as fr:
reader = csv.reader(fr)
for line in reader:
for x in l:
if line[0] == x[0]:
y.append([ line[0], int(x[1])+int(line[1]), int(x[2])+int(line[2]) ])
# Writes the values in temporary list to the same csv file
with open("namesList.csv", "w") as f:
writer = csv.writer(f)
for i in y:
writer.writerow(i)
假设