我正在尝试从我的 .csv 文件创建字典列表。我想将文件的第一行设为字典键,并将它们下面的列中的相应值设为它们的值。这已使用 .txt 文件成功完成,并且运行良好。当我尝试使用 .csv 格式执行此操作时,我遇到了无法调用特定 key 的问题,因此我认为它无法正常工作。
newqstars = [meteor['M_P'] for meteor in kept2]
>>>KeyError: 'M_P'
我整天都在尝试其他方法,例如 DictReader() 和 csv.reader(),但它们不起作用,所以我只想问我如何修改下面的内容以处理 .格式文件
def example_05(filename):
with open(filename,'r') as file : data = file.readlines()
header, data = data[0].split(), data[1:]
#................ convert each line to a dict, using header
# words as keys
global kept2
kept2 = []
for line in data :
line = [to_float(term) for term in line.split()]
kept2.append( dict( zip(header, line) ) )
if __name__ == '__main__' :
example_05('Geminids.csv')
请您参考如下方法:
DictReader 是去这里的方式:
import csv
with open('summ.csv') as csvfile:
reader = csv.DictReader(csvfile)
kept2 = [row for row in reader]
