似乎可以正常工作,问题是,它只返回csv文件的第一行,我在做什么错了?
我正在尝试将一个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)
答案 0 :(得分:2)
请在此处将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)
答案 1 :(得分:1)
您正在尝试将一项添加到词典中。 字典具有“键”:“值”对。 您所做的只是在字典中添加“值”。
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
答案 2 :(得分:0)
您正在执行任务:stockPxData = row
。这样只会在该变量中存储一个字典。
为了存储所有行,请尝试将它们附加到列表中,例如
stockPxData = []
for row in stockPxReader:
stockPxData.append(row)
或为每个dict元素定义要存储在dict中的键(这里我将数组中的索引用作键):
for idx, row in enumerate(stockPxReader):
stockPxData[str(idx)] = row