Michael
Michael

Reputation: 16122

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

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.

Upvotes: 8

Views: 19322

Answers (2)

Mukesh Chapagain
Mukesh Chapagain

Reputation: 25948

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]

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121416

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)

Upvotes: 18

Related Questions