I'm writing code to make a global dictionary from a CSV-file in Python. The code doesn't do what I expect.
users.csv
name,money_in_pocket
siem,10
bart,10
ivar,10
test.py
import csv
global users
users = {}
with open('users.csv', mode='r') as readuserfile:
readusers = csv.reader(readuserfile, delimiter=',')
next(readusers)
for rows in readusers:
users[rows[0]] = float(rows[1])
After running this piece of code, I expect the following to happen in the Shell:
>>>print(dict)
{'siem': 10, 'bart': 10, 'ivar': 10}
Instead, running test.py throws the next error:
Traceback (most recent call last):
----File "C:\\Users\\siemd\\Desktop\\test.py", line 8, in
--------users[rows[0]] = float(rows[1])
IndexError: list index out of range
If I understand this right, then the rows[0]
and rows[1]
cannot return a value, because they're out of the range of the 'list' (which is a read csv file).
But they should... Right?
You should check the length and type of rows
. Tried your example:
$cat t.py
import csv
global users
users = {}
with open('users.csv', mode='r') as readuserfile:
readusers = csv.reader(readuserfile, delimiter=',')
next(readusers)
for rows in readusers:
users[rows[0]] = float(rows[1])
print users
$cat users.csv
name,money_in_pocket
siem,10
bart,10
ivar,10
$python t.py
{'ivar': 10.0, 'bart': 10.0, 'siem': 10.0}
$
Works fine. But if there is a newline at the end it fails:
$cat >> users.csv
$python t.py
Traceback (most recent call last):
File "t.py", line 8, in <module>
users[rows[0]] = float(rows[1])
IndexError: list index out of range
$
Adding a simple check helps:
$cat t.py
...
for rows in readusers:
if len(rows)==2:
users[rows[0]] = float(rows[1])
...
$python t.py
{'ivar': 10.0, 'bart': 10.0, 'siem': 10.0}
$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.