Select Page

How to Solve Python AttributeError: ‘str’ object has no attribute ‘close’

by | Programming, Python, Tips

This error occurs when you try to close a string instead of a File object.

You can solve this error by keeping the open() call separate from the read() call so that the file object and file contents are under different variable names. Then you can close the file once you have accessed the contents.

The preferable way to handle the closing of files is to the with statement as a context manager, for example:

with open("example.txt", "r") as f:
    content = f.read()
    print(content)

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


AttributeError: ‘str’ object has no attribute ‘close’

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 close() method belongs to the File data type and closes an open file. It is good practice to close files after use. In some cases, changes made to a file may not show until the file is closed.

Example

Let’s look at an example where we want to read the contents of one file and append it to another. The first file contains the names of five celebrities:

Leonardo DiCaprio
Michael Jordan
Franz Kafka
Mahatma Gandhi
Albert Einstein

The second file contains the name of another famous historical figure.

Musa Keita I

Let’s look at the code to read the first file and append it’s contents to the second file:

file_content = open("celeb_names.txt", "r").read()
file_2 = open("celeb_names_extra.txt", "a").write(file_content)
file_content.close()

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [7], in <cell line: 3>()
      1 file_content = open("celeb_names.txt", "r").read()
      2 file_2 = open("celeb_names_extra.txt", "a").write(file_content)
----> 3 file_content.close()

AttributeError: 'str' object has no attribute 'close'

The error occurs because the variable file_content is a string, which contains the contents of the file and is not the file itself.

Solution #1: Use a context manager

Open files use resources and may be locked, preventing other programs from using them. It is good practice to use the with statement when accessing files as it automatically closes the file ones the code within its scope has finished. The with statement is the most widely used example of context managers, which allow us to allocate and release resources precisely when we want to. Let’s look at the revised code:

with open("celeb_names.txt", "r") as f, open("celeb_names_extra.txt", "a") as f_new:
   content = f.read()
   f_new.write(content)

Note that we can use the with statement more than one file. We opened the first file in read only mode and the second file in append mode as we do not want to overwrite its contents. We can run the code without error and then check the file celeb_names_extra.txt from the console to see the following contents:

Musa Keita I
Leonardo DiCaprio
Michael Jordan
Franz Kafka
Mahatma Gandhi
Albert Einstein

Solution #2: Use close() on File after read()

The alternative way to solve this error is to separate the open() call from the read() call. Making this change will ensure the file object and file contents are under separate file names. Then we can close the file object without trying to close the file contents, which is a string. Let’s look at the revised code:

f = open("celeb_names.txt", "r")
content = f.read()
f_new = open("celeb_names_extra.txt", "a")
f_new.write(content)
f.close()
f_new.close()

We can run the code without error and then check the file celeb_names_extra.txt from the console to see the following contents:

Musa Keita I
Leonardo DiCaprio
Michael Jordan
Franz Kafka
Mahatma Gandhi
Albert Einstein

Note that this method requires more lines of code and requires us to remember to close the files. The preferable method is to use the context manager as it automatically closes files after use.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors, go to the article:

How to Solve Python AttributeError: ‘Response’ object has no attribute ‘read’

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

Have fun and happy researching!