8

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.

2 Answers 2

18

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.