python - I get IndexError while still in the range -


i trying read rows of csv file. file looks this

col 1, col 2, col3 row11, row12, row13 row21, row22, row23 row31, row32, row33 ... 

i use following command read rows

with open('~/data.csv') f:     r = csv.dictreader(f)     in range(5):         print(list(r)[i]) 

the output prints first row, give out of index error right after.

indexerror                                traceback (most recent call last) <ipython-input-15-efcc4f8c760d> in <module>()       2     r = csv.dictreader(f)       3     in range(5): ----> 4         print(list(r)[i])  indexerror: list index out of range 

i'm guessing i'm making silly mistake somewhere, can't spot it. ideas on doing wrong , how fix it?

edit: output of print(list(r)):

[{'col 1': 'row11', ' col3': ' row13', ' col 2': ' row12'}, {'col 1': 'row21', ' col3': ' row23', ' col 2': ' row22'}, {'col 1': 'row31', ' col3': ' row33', ' col 2': ' row32'}, {'col 1': 'row41', ' col3': ' row43', ' col 2': ' row42'}, {'col 1': 'row51', ' col3': ' row53', ' col 2': ' row52'}, {'col 1': 'row61', ' col3': ' row63', ' col 2': ' row62'}, {'col 1': 'row71', ' col3': ' row73', ' col 2': ' row72'}, {'col 1': 'row81', ' col3': ' row83', ' col 2': ' row82'}, {'col 1': 'row91', ' col3': ' row93', ' col 2': ' row92'}, {'col 1': 'row101', ' col3': ' row103', ' col 2': ' row102'}] 

dictreader(f) gives 1 time @ file -- can call list on once, call multiple times because it's within loop. later calls return empty list. call list on outside of loop , save in variable, , you'll golden.

that is:

r = csv.dictreader(f) rows = list(r) in range(5):     print(rows[i]) 

or, don't pull whole thing memory @ point:

for row in csv.dictreader(f):     print row 

if you'd keep index around other purposes:

 i, row in enumerate(csv.dictreader(f)):      print i, row 

if want specific rows iterator (which csv.dictreader special case of) without pulling whole thing memory, check out itertools.islice @ https://docs.python.org/3/library/itertools.html. allows list-style slicing on iterator.

  # prints first 5 rows   row in itertools.islice(csv.dictreader(f), 5):        print row 

for more sporadic rows:

  needed_row_indices = {2, 5, 20}   i, row in enumerate(csv.dictreader(f)):       if in needed_row_indices:           print row 

Popular posts from this blog