我试图将 .csv 的每一行转换为字典(键是 .csv 的第一行),然后我试图将这些字典中的每一个放入一个列表中。当我运行此代码时,我最终将 .csv 的 LAST ROW 一遍又一遍地附加到列表中,而不是正确地将每个字典(临时保存为 dataLine)附加到列表中?这更加令人困惑,因为如果我将代码中的“dataList.append(dataLine)”行替换为“print dataLine”,代码将遍历 .csv 并单独打印每一行,而不是一遍又一遍地打印最后一行再次。
from sys import argv
import csv
# arguments
script, csvFile = argv
# check input
while csvFile.endswith(".csv") == False:
csvFile = raw_input("Please enter a *.csv file: ")
# open the csv file
openFile = open(csvFile, 'r')
# read the csv file
reader = csv.reader(openFile, delimiter=',')
# extract first row to use as keys
for row in range(1):
keys = reader.next()
# turn rows into dictionaries with keys
#FIX THIS PART!! NOT WORKING RIGHT!!!
length = len(keys)
dataLine = {}
dataList = []
for row in reader:
for i in range(length):
dataLine[keys[i]] = row[i]
dataList.append(dataLine)
for x in dataList:
print x
print ""
# close the file
openFile.close()