Select Page

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

by | Programming, Python

This error occurs when you try to call the append() method on a File object. The append() method is an attribute of the String class, not _io.TextIOWrapper. If you want to write new data to a file, you can open the file in append mode and then write the latest data by calling the write() method.

You can get the contents of the file as a list using readlines() and then strip the new line characters using the strip method as follows:

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

Once you have a list, you can append further data by calling the append() method.

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


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

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 append method is an attribute of the List class, not the _io.TextIOWrapper class.

Example

Consider the following text file containing the names of five celebrities:

Leonardo DiCaprio
Michael Jordan
Franz Kafka
Mahatma Gandhi
Albert Einstein

We will save the celebrity names under the filename ‘celeb_names.txt‘. Next, we will attempt to read the data into a program and append three other celebrity names to the file object using the append() method.

more_names= ["Paul Dirac", "Marie Curie", "Zadie Smith"]

with open('celeb_names.txt', 'r') as f:

    for name in more_names:

        f.append(name)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [9], in <cell line: 3>()
      3 with open('celeb_names.txt', 'r') as f:
      4     for name in more_names:
----> 5         f.append(name)

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

The error occurs because we try to call append() on the File object returned by the open() function call. The append() method is an attribute of the List class. We can find out what attributes an object has with the built-in dir() function, for example:

with open('celeb_names.txt', 'r') as f:
    attributes = dir(f)
    print('append' in attributes)

We checked for membership of the append method in the list of attributes for the File object returned by the dir() function. The result is False, confirming that append is not a TextIOWrapper method. The list of available attributes for the File object is as follows:

with open('celeb_names.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']

Solution #1

If we want to write new data to a file, we can open the file in append mode by using 'a' as the second argument of the open() function. We can then use a for loop to iterate over the celebrity names in the more_names list and write each name to the file.

We will also write a new line character ('\n')to ensure each name is on a new line. Let’s look at the revised code:

more_names= ["Paul Dirac", "Marie Curie", "Zadie Smith"]

with open('celeb_names.txt', 'a') as f:

    for name in more_names:

        f.write(name)
        f.write('\n')

Once we run this code, we can open the celeb_names.txt file and see the three new celebrity names.

Leonardo DiCaprio
Michael Jordan
Franz Kafka
Mahatma Gandhi
Albert Einstein
Paul Dirac
Marie Curie
Zadie Smith           

Solution #2

If we want to store all the celebrity names in a list, we can call the readlines() method on the File object, which returns a list.

We can then use strip() method on each string in the list to remove the new line characters.

Once we have a list of stripped strings, we can iterate over the more_names list and append the strings in that list to the list of existing celebrity names.

Let’s look at the updated code:

more_names= ["Paul Dirac", "Marie Curie", "Zadie Smith"]
with open('celeb_names.txt', 'r') as f:
    lines = f.readlines()
    lines = [line.strip() for line in lines]
    for name in more_names:
        lines.append(name)
    print(lines)

Let’s run the code to see the result:

['Leonardo DiCaprio', 'Michael Jordan', 'Franz Kafka', 'Mahatma Gandhi', 'Albert Einstein', 'Paul Dirac', 'Marie Curie', 'Zadie Smith']

We successfully appended the three new celebrity names to the list of celebrity names retrieved from the celeb_names.txt file.

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!