Select Page

How to Solve Python TypeError: ‘_io.TextIOWrapper’ object is not subscriptable

by | Programming, Python, Tips

In Python, you cannot access values inside a File object using indexing syntax. Indexing syntax is suitable for subscriptable objects such as strings or lists. If you attempt to retrieve an item from a File object, you will raise the “TypeError: ‘_io.TextIOWrapper’ object is not subscriptable”.

You can solve this error by calling the readlines() method on the File object, which will return a list.

This tutorial will go through how to solve this error with code examples.


TypeError: ‘_io.TextIOWrapper’ object is not subscriptable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “_io.TextIOWrapper object” tells us the error is due to an illegal operation with a File object.

The part “is not subscriptable” tells us we cannot access an element of a File object using the subscript operator [].

A subscriptable object is a container for other objects and implements the __getitem__() method. Examples of subscriptable objects include strings, lists, tuples, and dictionaries.

We can check if an object implements the __getitem__() method by listing its attributes with the dir function. Let’s call the dir function and pass a list and a file to see their attributes.

lst = [1, 2, 3]
print(dir(lst))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
with open('leptons.txt', 'r') as f:
    print(dir(f))
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']

If you want to check if a specific attribute belongs to an object, you can check for membership using the in operator.

lst = [1, 2, 3]
print('__getitem__' in dir(list))
True

We can see that __getitem__ is an attribute of the List data type.

with open('leptons.txt', 'r') as f:
    print('__getitem__' in dir(f))
False

We can see that __getitem__ is not an attribute of the File data type.

Example

Let’s look at an example of a text file called leptons.txt containing the names of three particles.

muon
electron
tau

We will attempt to read the file into our program using a context manager and print the first line of the file using the subscript operator.

with open('leptons.txt', 'r') as f:
    print(f[0])

Let’s run the code to see the result:

------------------------------------------------------------------------
TypeError                              Traceback (most recent call last)
Input In [26], in <cell line: 1>()
      1 with open('leptons.txt', 'r') as f:
----> 2     print(f[0])

TypeError: '_io.TextIOWrapper' object is not subscriptable

The error occurs because we are trying to use the subscript operator on the File object f. The subscript operator is only suitable for subscriptable objects like lists or strings.

Solution

We can solve the error by calling the readlines() method on the file object, which returns a list containing the lines in the file. We can access the first item in the list using the subscript operator. Let’s look at the updated code:

with open('leptons.txt', 'r') as f:
    lines = f.readlines()
    print(type(lines))
    print(lines[0])

Let’s run the code to see the result:

<class 'list'>
muon

We can see from the print statements that the lines object is a list, and we successfully retrieved the first item using the subscript operator.

We can also iterate over the list using a for loop and print each item with the following code.

with open('leptons.txt', 'r') as f:
    lines = f.readlines()
    lines = [line.strip() for line in lines]
    for line in lines:
        print(line)

Let’s run the code to see the result:

muon
electron
tau

We successfully iterated over the list and printed each item to the console.

Summary

Congratulations on reading to the end of this tutorial.

For further reading on TypeErrors, go to the articles:

To learn more about Python for data science and machine learning, you can go to the online courses page on Python for the most comprehensive courses.

Have fun and happy researching!