Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: '_csv.reader' object has no attribute '__getitem__'?

Tags:

python

csv

Here is my code so far:

import csv
reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
row1 = reader[0]
row2 = reader[1]
row3 = reader[2]

Here is my new_file.txt:

this is row one
this is row two
this is row three

When I run It i have the following error:

Traceback (most recent call last):
  File "/home/me/Documents/folder/file.py", line 211, in <module>
    row1 = reader[0]
TypeError: '_csv.reader' object has no attribute '__getitem__'

How can I fix that?

Thanks.

like image 896
Michael Avatar asked Sep 30 '13 09:09

Michael


2 Answers

A csv.reader() object is not a sequence. You cannot access rows by index.

You'd have to 'slurp' the whole iterable into a list for that:

rows = list(reader)
row1 = rows[0]
row2 = rows[1]
row3 = rows[2]

This is generally not a good idea. You can instead ask for the next value from the iterator with the next() function:

reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
row1 = next(reader)
row2 = next(reader)
row3 = next(reader)
like image 53
Martijn Pieters Avatar answered Oct 20 '22 08:10

Martijn Pieters


You can loop the reader and then access the row elements:

import csv
reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
for row in reader:
    row1 = row[0]
    row2 = row[1]
    row3 = row[3]
like image 29
Mukesh Chapagain Avatar answered Oct 20 '22 09:10

Mukesh Chapagain