0
votes

I'm attempting to read CSV data line-by-line, isolate 1 piece of data in each line and print it out.

Sample from CSV:

Date,Open,High,Low,Last,Change,Settle,Volume,Prev. Day Open Interest
1969-06-25,22.0,22.0,22.0,,,22.0,3.0,3.0
1969-06-26,23.0,23.0,21.9,,,21.9,6.0,9.0

My code:

file1 = 'LNG1970'

infile = open(('%s.csv' % file1), 'r')

for line in infile.readlines():
    (d, o, h, l, la, ch, s, v, o) = line.split(",")
    print(d)

Error returned in console:

Traceback (most recent call last):
File "", line 1, in
File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile execfile(filename, namespace)
File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Nutrade/Desktop/Python/Quandl Hog Project/spreadmaker.py", line 6, in (d, o, h, l, la, ch, s, v, o) = line.split(",")
ValueError: need more than 1 value to unpack

Can somebody please explain why this is happening and how to rectify?

2
Looks like you hit a blank line or one with no commas.martineau

2 Answers

0
votes

Your code works fine. As discussed here, you probably have one or more blank lines at the end of your CSV file. (It's hard to tell from your question because the CSV file is not formatted nicely. Please refer here for help on formatting your text using Markdown.)

0
votes

Try assigning to a temporary and skipping if length is incorrect before trying to unpack.

for line in infile.readlines():
    temp = line.split(",")
    if not len(temp) == 9:
        continue
    (d, o, h, l, la, ch, s, v, o) = temp
    print(d)