I get IndexError while still in range

I am trying to read the lines of a csv file. My file looks like this:

Col 1, Col 2, Col3 row11, row12, row13 row21, row22, row23 row31, row32, row33 ... 

I use the following command to read lines

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

The output prints the first line, but then immediately produces an index error.

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

I suppose that I am making a stupid mistake somewhere, but I cannot notice it. Any ideas on what I'm doing wrong and how to fix it?

EDIT:. This is the result 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'}] 
+2
source share
1 answer

DictReader(f) just gives you a look at your file once - you can only call it t21, but you call it several times because it is in a loop. Calls later return an empty list . Just name list on it outside the loop and store it in a variable and you will become golden.

I.e:

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

Or, do not put it all into memory at any time:

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

If you want to keep the index for other purposes:

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

If you want to get specific lines from iterator (which csv.DictReader is a special case) without pulling all this into memory, check itertools.islice at https://docs.python.org/3/library/itertools.html . This basically allows a list line slice on the iterator .

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

For more sporadic lines:

  needed_row_indices = {2, 5, 20} for i, row in enumerate(csv.DictReader(f)): if i in needed_row_indices: print row 
+4
source

All Articles