How to Solve Python AttributeError: ‘_io.TextIOWrapper’ object has no attribute ‘next’

by | Programming, Python, Tips

This error occurs when you try to call the next() method on a File object. next() is a built-in Python function. You can solve this error by calling the next() function and passing the File object as the argument, for example:

next(file_obj)

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


AttributeError: ‘_io.TextIOWrapper’ object has no attribute ‘next’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The next() function is a built-in function, which returns the next item from an iterator by calling its __next__() method.

Example

Consider the following text file called pizzas.txt containing the names of pizzas.

name
margherita
pepperoni
four cheeses
ham and pineapple
chicken and sweetcorn
meat feast
marinara

We want to write the pizza names less than 12 characters in length to a new file called pizzas_v2.txt. The first line in the file is not a pizza name, so we want to skip that line using the next() function.

with open('pizzas.txt', 'r') as f, open('pizzas_v2.txt', 'w') as g:
    f.next()
    for line in f:
        if len(line) < 12:
            g.write(line)
            g.write('\n')

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [2], in <cell line: 1>()
      1 with open('pizzas.txt', 'r') as f, open('pizzas_v2.txt', 'w') as g:
----> 2     f.next()
      3     for line in f:
      4         if len(line) < 12:

AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

The error occurs because next() is a built-in function, not an attribute of _io.TextIOWrapper. When we use a for loop, we iterate over lines in the File object.

An iterator is an object that helps us iterate through the iterable, which we create when we call the __iter__ method on an iterable, which in this case is the File object.

The iterator has a method called __next__, which returns the next item in the iterable.

We can get the attributes of an iterator by using the dir() function as follows:

with open('pizzas.txt', 'r') as f:
    print(dir(f.__iter__()))

Note that we get the iterator object by calling __iter__() on the File object, 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']

We can check for membership in the list of attributes using the in operator as follows:

with open('pizzas.txt', 'r') as f:
    print('__next__' in dir(f.__iter__()))
True

The for loop in our example code invokes the __iter__ method on the File object f to create an iterator object.

Solution

We can solve the error by calling the next() function and passing the File object as the argument. The next() function will invoke the __next__ method on the iterator for the file object, f. When we start the for loop, the first iteration will start with the file’s second line. Let’s look at the revised code:

with open('pizzas.txt', 'r') as f, open('pizzas_v2.txt', 'w') as g:
    next(f)
    for line in f:
        if len(line) < 12:
            g.write(line)

Once we run the code, we can open the file pizzas_v2.txt and see the following pizza names:

margherita
pepperoni
meat feast
marinara

Summary

Congratulations on reading to the end of this tutorial.

For further reading on errors involving TextIOWrapper, go to the article:

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨