Sean Low
Sean Low

Reputation: 51

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?

I'm trying to import a csv file into my python code but it only returns the first line of the csv file

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)   

Upvotes: 0

Views: 1308

Answers (3)

Akiem Paul
Akiem Paul

Reputation: 31

You are trying to add an item to a dictionary. Dictionaries have 'key':'value' pair. 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

Upvotes: 1

vinodsesetti
vinodsesetti

Reputation: 418

here please change stockPxData = {} to stockPxData = [] and then append row to stockPxData list.

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)

Upvotes: 1

Martin
Martin

Reputation: 644

You are just perform an assignment: stockPxData = row. This results in only one dict being stored in this variable.

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):

for idx, row in enumerate(stockPxReader):
    stockPxData[str(idx)] = row

Upvotes: 0

Related Questions