我试图将 .csv 的每一行转换为字典(键是 .csv 的第一行),然后我尝试将每个字典放入一个列表中。当我运行此代码时,我最终一遍又一遍地将 .csv 的最后一行附加到列表中,而不是正确地将每个字典(临时保存为 dataLine)附加到列表中?这更加令人困惑,因为如果我用“print dataLine”替换代码中的“dataList.append(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()
最佳答案
您可以尝试的一件事是使用内置 DictReader csv
中的类:
>>> import csv
>>> with open('fake_csv.csv', 'r') as f:
... reader = csv.DictReader(f)
... my_rows = [row for row in reader]
...
>>> my_rows
[{'title1': 'something', 'title2': 'another'}, {'title1': 'cool', 'title2': 'stuff'}]
DictReader
实际上执行您所描述的操作 - 它使用第一行作为列标题,并从每个后续行创建一个字典,其中键是列标题,值是该行的列。使用 with
是确保文件在不再需要时正确关闭的一种方法,这一行:
my_rows = [row for row in reader]
是list comprehension迭代reader
并将每一行放入结果列表中(标题行除外)。
这里我使用了如下所示的 CSV:
title1,title2
something,another
cool,stuff
关于python - 明显的循环问题 : Why am I appending the same thing to my list over and over again?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444126/