bushc
bushc

Reputation: 11

Python3 CSV reader ValueError

I searched through the python csv questions, can't seem to find anything addressing the reader error I'm getting.

I have a csv file with 6 columns, trying to access two of them:

import csv

with open('/home/conjugater/Downloads/aapl.csv', newline='') as csvfile:
  dialect=csv.Sniffer().sniff(csvfile.read(1024))
  csvfile.seek(0)
  reader=csv.reader(csvfile, dialect)
  for row in reader:
      for Date, Open, High, Low, Close, Volume in row:
          print(Date, Close)

I'm not done coding, but this is my first time using the csv module and I'm just trying to get a feel for it (relatively new to python in general).

Traceback (most recent call last):
File "reader.py", line 8, in <module>
for Date, Open, High, Low, Close, Volume in row:
ValueError: need more than 5 values to unpack

I can get the columns I want with

for row in reader:
    print(row[0], row[4])

but I know there's a way to assign each column a name with python as well; any help much appreciated.

Upvotes: 0

Views: 567

Answers (3)

hd1
hd1

Reputation: 34657

You're close, but you need to use

with open('/home/conjugater/Downloads/aapl.csv', newline='') as csvfile:
  dialect=csv.Sniffer().sniff(csvfile.read(1024))
  csvfile.seek(0)
  reader=csv.DictReader(csvfile, dialect, fieldnames = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'])
  for row in reader:
      for Date, Open, High, Low, Close, Volume in row:
          print("{}: {}".format(Date, Close))

Hope that helps....

Upvotes: 1

nofinator
nofinator

Reputation: 3023

You have 2 for loops when you only need one:

for (Date, Open, High, Low, Close, Volume) in reader:
    print(Date, Close)

Upvotes: 3

hanleyhansen
hanleyhansen

Reputation: 6452

Why are you assigning newline=''? That tells open() to treat each empty string as the end of a line. Try this instead: newline='\n'. Or try it without passing newline.

Vor's comment below is useful too. See docs on open for more information.

Upvotes: 1

Related Questions