Dineshkumar
Dineshkumar

Reputation: 1548

Python 3 - CSV File Issue (ValueError: not enough values to unpack)

I tried modifying this example code on python 3.x.

import csv

def cmp(a, b):
    return (a > b) - (a < b)

# write stocks data as comma-separated values
f = open('stocks.csv', 'w')
writer = csv.writer(f)
writer.writerows([
    ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),
    ('YHOO', 'Yahoo!, Inc.', 27.38, 0.33, 1.22),
    ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49)
])

f.close()

# read stocks data, print status messages
f = open('stocks.csv', 'r')
stocks = csv.reader(f)
status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}
for ticker, name, price, change, pct in stocks:
    status = status_labels[cmp(float(change), 0.0)]
    print('%s is %s (%s%%)' % (name, status, pct))

f.close()

With suggestions from @glibdud, and @bernie, I have updated my code. Am getting the below error:

ValueError: not enough values to unpack (expected 5, got 0)

What am I missing?

Note: Removed my question about double quotes in CSV file for string. Double quotes will be there if we have comma separated string, otherwise not.

Upvotes: 0

Views: 1844

Answers (1)

DahliaSR
DahliaSR

Reputation: 77

The Problem occurs during writing the file. The problem is the newline handling of the csv module. See this and footnote 1

if you add print(*stocks, sep='\n') between line 19 ans 20 you will get following output:

['GOOG', 'Google, Inc.', '505.24', '0.47', '0.09']
[]
['YHOO', 'Yahoo!, Inc.', '27.38', '0.33', '1.22']
[]
['CNET', 'CNET Networks, Inc.', '8.62', '-0.13', '-1.49']
[]

You see... an empty list can not have 5 values to unpack

@bernie already gave you the solution in his comment.
Change line 7 to:

f = open('stocks.csv', 'w', newline='')
                          ^^^^^^^^^^^^

and you're fine.

Upvotes: 1

Related Questions