The TypeError object: '_csv.reader' does not have the attribute '__getitem__'?

Here is my code:

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 launched 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 this?

Thanks.

+6
source share
2 answers

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

You will need a "slurp" integer iterable to the list for this:

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

This is usually not a good idea. Instead, you can query the following value from an iterator using the next() function:

 reader = csv.reader(open('new_file.txt','r'),delimiter=' ') row1 = next(reader) row2 = next(reader) row3 = next(reader) 
+16
source

You can execute the reader loop 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] 
+2
source

Source: https://habr.com/ru/post/954926/


All Articles