python - 明显的循环问题 : Why am I appending the same thing to my list over and over again?

标签 python csv

我试图将 .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/

相关文章:

JAVA解析txt文件中的数据

r - 如何将多个表、数据框、回归结果等写入一个 Excel 文件?

python - 迭代 EOD .csv 以在每个文件中创建历史运行高点、低点

python - 我可以使用 ctypes 从 C 中嵌入的 python 回调 C 函数吗?

python - 如何在pycharm中从中心旋转一个对象?

python - 在 Python 中使用 RDD 与 Spark SQL 计算标准偏差

python - 使用 scipy 的 SmoothSphereBivariateSpline 进行插值

python - 我们如何在frappe中动态添加子表(ERPNEXT)

java - 将动态 SQL 查询保存到 CSV?

json - 如何优化此Powershell脚本,将JSON转换为CSV?