[英]csv.DictReader function only reading first line of csv file
Seems to work, the problem is, it only returns the first line of the csv file, what am I doing wrong?似乎有效,问题是,它只返回 csv 文件的第一行,我做错了什么?
I'm trying to import a csv file into my python code but it only returns the first line of the csv file我正在尝试将 csv 文件导入到我的 python 代码中,但它只返回 csv 文件的第一行
import csv
with open('aapl_price-history-01-09-2019.csv') as csvfile:
fieldnames = ['Time', 'Open', 'High', 'Low', 'Last', 'Change', 'Volume']
stockPxReader = csv.DictReader(csvfile)
stockPxData = {}
for row in stockPxReader:
stockPxData = row
print(stockPxData)
here please change stockPxData = {} to stockPxData = [] and then append row to stockPxData list.在这里,请将 stockPxData = {} 更改为 stockPxData = [],然后将行附加到 stockPxData 列表。
import csv
with open('aapl_price-history-01-09-2019.csv') as csvfile:
fieldnames = ['Time', 'Open', 'High', 'Low', 'Last', 'Change',
'Volume']
stockPxReader = csv.DictReader(csvfile)
stockPxData = []
for row in stockPxReader:
stockPxData.append(row)
print(stockPxData)
You are trying to add an item to a dictionary.您正在尝试向字典中添加一个项目。 Dictionaries have 'key':'value' pair.
字典有 'key':'value' 对。 what you are doing is only adding the 'value' to the dictionary.
您正在做的只是将“值”添加到字典中。
import csv
with open('aapl_price-history-01-09-2019.csv') as csvfile:
fieldnames = ['Time', 'Open', 'High', 'Low', 'Last', 'Change', 'Volume']
stockPxReader = csv.DictReader(csvfile)
stockPxData = {}
idx = 0 # this is to initialize the index counter
for row in stockPxReader:
stockPxData[str(idx)] = row # syntax to assign key value to dict
idx = idx + 1 # update index value in the for loop
print(stockPxData) # print in the open file handler statement
You are just perform an assignment: stockPxData = row
.您只是执行一项任务:
stockPxData = row
。 This results in only one dict being stored in this variable.这导致只有一个 dict 被存储在这个变量中。
In order to store all rows, try to append them to an list, like为了存储所有行,请尝试将它们附加到列表中,例如
stockPxData = []
for row in stockPxReader:
stockPxData.append(row)
or define a key for each dict element to store in the dict (here I use the index in the array as a key):或者为每个 dict 元素定义一个键以存储在 dict 中(这里我使用数组中的索引作为键):
for idx, row in enumerate(stockPxReader):
stockPxData[str(idx)] = row
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.