我正在尝试编写一个 python 脚本,该脚本将从 CSV 文件中获取输入,然后将其推送为字典格式(我使用的是 Python 3.x)。
我使用下面的代码读取 CSV 文件,并且可以正常工作:
import csv
reader = csv.reader(open('C:\\Users\\Chris\\Desktop\\test.csv'), delimiter=',', quotechar='|')
for row in reader:
print(', '.join(row))
但现在我想将结果放入字典中。我希望 CSV 文件的第一行用作字典的“键”字段,CSV 文件中的后续行填写数据部分。
样本数据:
Date First Name Last Name Score
12/28/2012 15:15 John Smith 20
12/29/2012 15:15 Alex Jones 38
12/30/2012 15:15 Michael Carpenter 25
我还想用这段代码做一些额外的事情,但现在我正在寻找的是让字典正常工作。
谁能帮我这个?
编辑版本 2:
import csv
reader = csv.DictReader(open('C:\\Users\\Chris\\Desktop\\test.csv'))
result = {}
for row in reader:
for column, value in row.items():
result.setdefault(column, []).append(value)
print('Column -> ', column, '\nValue -> ', value)
print(result)
fieldnames = result.keys()
csvwriter = csv.DictWriter(open('C:\\Users\\Chris\\Desktop\\test_out.csv', 'w'), delimiter=',', fieldnames=result.keys())
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
for row in result.items():
print('Values -> ', row)
#csvwriter.writerow(row)
'''
Test output
'''
test_array = []
test_array.append({'fruit': 'apple', 'quantity': 5, 'color': 'red'});
test_array.append({'fruit': 'pear', 'quantity': 8, 'color': 'green'});
test_array.append({'fruit': 'banana', 'quantity': 3, 'color': 'yellow'});
test_array.append({'fruit': 'orange', 'quantity': 11, 'color': 'orange'});
fieldnames = ['fruit', 'quantity', 'color']
test_file = open('C:\\Users\\Chris\\Desktop\\test_out.csv','w')
csvwriter = csv.DictWriter(test_file, delimiter=',', fieldnames=fieldnames)
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
for row in test_array:
print(row)
csvwriter.writerow(row)
test_file.close()