Skip to content

[Solved][Python] "_csv.reader" object is not subscriptable

Last Updated on 2022-07-24 by Clay

Problem

Today, I checked the code left by my predecessors, I found a strange problem. I think, that is the code that the predecessors discarded that are not in use and just haven't been deleted.

It looks like Python is using the built-in csv module to read the data, but it occurs the following error:

"_csv.reader" object is not subscriptable


In order to make the code work normally, I inquired about the troubleshooting method of this problem and recorded it as follows.

If I remember correctly, I had this problem once a few years ago. In order not to get stuck with this problem in a few years, I think I need to document the problem honestly.


Solution

According to the error message, the _csv.reader does not actually support the use of index values, it returns an iterator.

So when we use something like:

print(csv_data[0])


... to take the value, the error shown at the beginning of the article will appear. We need to use the for-loop to read the data line by line; if you really need to get the data through the index, you can consider turning the iterator into a list structure.

list(csv_data)

References


Read More

Tags:

Leave a Reply