If you are a beginner in Python, it will be difficult when reading a CSV file. This article will explain the root of the error “TypeError: ‘_csv.reader’ object is not subscriptable” and provide a few solutions to the problem.
The error “TypeError: ‘_csv.reader’ object is not subscriptable”
The TypeError: ‘_csv.reader’ object is not subscriptable error usually occurs when you try to index or slice a csv.reader object, which is not allowed.
For example, the following code would trigger this error:
Code:
# Import required library import csv from contextlib import closing import requests # URL to read CSV file directly url = "https://raw.githubusercontent.com/VN-huster/LearnShareIT/main/planets.csv" with closing(requests.get(url, stream=True)) as f: line = (line.decode('utf-8') for line in f.iter_lines()) data = csv.reader(line) # Access the index of the csv.reader object and get the error print(data[0]) # <-- Error here
Result:
TypeError Traceback (most recent call last)
in <module>
---> 14 print(data[0]) ## <-- Error here
TypeError: '_csv.reader' object is not subscriptable
This error occurs because csv.reader returns an iterator that reads the rows of the CSV file one by one rather than returning a list of rows that can be indexed.
Note: In the example above, we use a link to access the CSV file from Github. It is fine to read a CSV file on your local machine.
Solution to the error
Remember that the error occurs because it is wrong when accessing the index or slice of a csv.reader object. It means you can not access the object’s special position or interval elements.
Loop over the csv.reader object
To access the rows of a CSV file, you can use a loop to iterate over the csv.reader object and process each row individually. Look at the following example to see more detail.
Code:
# Import required library import csv from contextlib import closing import requests # URL to read CSV file directly url = "https://raw.githubusercontent.com/VN-huster/LearnShareIT/main/planets.csv" with closing(requests.get(url, stream=True)) as f: line = (line.decode('utf-8') for line in f.iter_lines()) data = csv.reader(line) # Loop over the csv.reader object to get elements for element in data: print(element)
Result:
['Planet', 'Color']
['Mercury', 'Grey']
['Venus', 'Brown and Grey']
['Earth', 'Blue, Brown Green and White']
['Mars', 'Red, Brown and Tan']
['Jupiter', 'Brown, Orange and Tan, with White cloud stripes']
['Saturn', 'Golden, Brown, and Blue-Grey']
['Uranus', 'Blue-Green']
['Neptune', 'Blue']
Use the ‘’csv.DictReader’’ class
Alternatively, you can use the csv.DictReader class, which returns a list of dictionaries, where each dictionary represents a row in the CSV file with the column names as keys and the cell values as values. You can then access the rows of the CSV file using the column names as keys. For example:
Code:
# Import required library import csv from contextlib import closing import requests # URL to read CSV file directly url = "https://raw.githubusercontent.com/VN-huster/LearnShareIT/main/planets.csv" with closing(requests.get(url, stream=True)) as f: line = (line.decode('utf-8') for line in f.iter_lines()) data = csv.DictReader(line) for element in data: print(element)
Result:
{'Planet': 'Mercury', 'Color': 'Grey'}
{'Planet': 'Venus', 'Color': 'Brown and Grey'}
{'Planet': 'Earth', 'Color': 'Blue, Brown Green and White'}
{'Planet': 'Mars', 'Color': 'Red, Brown and Tan'}
{'Planet': 'Jupiter', 'Color': 'Brown, Orange and Tan, with White cloud stripes'}
{'Planet': 'Saturn', 'Color': 'Golden, Brown, and Blue-Grey'}
{'Planet': 'Uranus', 'Color': 'Blue-Green'}
{'Planet': 'Neptune', 'Color': 'Blue'}
Create a list of rows
When calling the csv.reader() function, you can use the list()
function to make them become a list. As a result, you can index or slice to access the new object
Code:
# Import required library import csv from contextlib import closing import requests # URL to read CSV file directly url = "https://raw.githubusercontent.com/VN-huster/LearnShareIT/main/planets.csv" with closing(requests.get(url, stream=True)) as f: line = (line.decode('utf-8') for line in f.iter_lines()) # Create a list of rows data data = list(csv.reader(line)) print(data[1:4])
Result:
[['Mercury', 'Grey'], ['Venus', 'Brown and Grey'], ['Earth', 'Blue, Brown Green and White']]
Summary
In summary, the error “TypeError: ‘_csv.reader’ object is not subscriptable” occurs when you index or slice a csv.read object. If you want to get a special position, make them become a list to access indexes. In case you want to get elements, just loop over them.
My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.
Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP