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):
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'}]