TypeError: '_io.TextIOWrapper' object is not subscriptable

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

TypeError: '_io.TextIOWrapper' object is not subscriptable #

The Python "TypeError: '_io.TextIOWrapper' object is not subscriptable" occurs when we try to use square brackets to access a key or index in a file object. To solve the error, use the readlines() method if you need a list of the file's lines, or parse the JSON before accessing a key.

typeerror io textiowrapper object is not subscriptable

Here is an example of how the error occurs.

main.py
with open('example.txt', 'r', encoding='utf-8') as f: # ⛔️ TypeError: '_io.TextIOWrapper' object is not subscriptable print(f[0])

We use square brackets to try to access the element at index 0, but the TextIOWrapper object is not subscriptable.

In this scenario, we have to use the readlines() method to read all the lines of the file.

main.py
with open('example.txt', 'r', encoding='utf-8') as f: # ✅ get list of all lines lines = f.readlines() print(lines) print(lines[0]) for line in lines: print(line)

If you need to read all the lines of a file in a list, use the f.readlines() method.

Another common cause of the error is trying to read from a JSON file without parsing the content into a native Python object first.

Imagine we have an example.json file with the following content.

example.json
{ "name": "Alice", "age": 30 }

If we try to access a key without having parsed the data we would get the error.

main.py
file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: # ⛔️ TypeError: '_io.TextIOWrapper' object is not subscriptable print(f['name'])

To get around this, we have to use the json.load() method.

main.py
import json with open('example.json', 'r', encoding='utf-8') as f: # ✅ deserialize file to Python object my_data = json.load(f) print(my_data) # 👉️ {'name': 'Alice', 'age': 30} print(my_data['name']) # 👉️ 'Alice' print(my_data['age']) # 👉️ 30

The json.load method is used to deserialize a file to a Python object.

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method.

If you try to access a key without having parsed the file object into a native Python object, the error occurs.

The "TypeError: object is not subscriptable" means that we are using square brackets to either access a key in a specific object or to access a specific index, however the object doesn't support this functionality.

Use the search field on my Home Page to filter through my more than 1,000 articles.