In Python, we can read and write to files using the with statement with the open() function. The open() function opens a file and returns a file object. The file object exposes a file-oriented API, with methods such as read() or write() to the underlying resource.

If we want to write to a file, we have to call the File method write() on the file object with the text to write as the argument.

If we try to call the write() method on the text we want to write to file, we will get the AttributeError: ‘str’ object has no attribute ‘write’.

To solve this error, ensure that you call the write() method on the file object returned by the open() function.

This tutorial will go through the error in detail and how to solve it with code examples.


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

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 part “‘str’ object has no attribute ‘write’” tells us that the string object does not have the attribute write(). The write() method belongs to the File class and writes to a file. The syntax of the write() method is as follows:

file.write(str)

Parameters

  • str: Required. String to write to file.

Example

We can open a file using the open function, for example:

f = open('test.txt', 'w')

f.write('Adding text')

f.close()

The first parameter in the open() function is the name of the file as a string and the second parameter determines how we write to a file. In this case, 'w' means we will overwrite any existing content in the file test.txt.

The preferred method to read or write to a file is to use the open function with the with keyword. This pattern is also known as a context manager, which facilitates the proper handling of resources. The file automatically closes when we exit the code black created using the with open pattern. When using this pattern, we have to create a variable name for the file object returned by the open function. Let’s look at an example:

outfile = 'particles.txt'

particles_list = ['electron', 'muon', 'positron', 'neutrino', 'higgs boson']

with open(outfile, 'w') as f:

    for p in particles_list:

        outfile.write(p+'\n')

In the above code, we define a name for the file. Then we define a list of strings representing the names of particles. Next, we use the with open pattern to open the file and create a file object called f. We then try to write each string in the list to the file using a for loop. Let’s run the code to see the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-d4041836fd48> in <module>
      5 with open(outfile, 'w') as f:
      6     for p in particles_list:
----> 7         outfile.write(p+'\n')
      8 

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

The Python interpreter throws the AttributeError because we call the write() method on the file’s name, which is a string, and not the file object.

Solution

To solve this error, we need to call the write() method on the file object f. Let’s look at the revised code.

outfile = 'particles.txt'

particles_list = ['electron', 'muon', 'positron', 'neutrino', 'higgs boson']

with open(outfile, 'w') as f:

    for p in particles_list:

        f.write(p+'\n')

Once we run the code, a file called particles.txt will be in the directory where your Python script exists. The file will have each particle’s name on a separate line.

Summary

Congratulations on reading to the end of this tutorial! The AttributeError: ‘str’ object has no attribute ‘write’ occurs when you try to call the write() method on a string instead of a file object. This error can happen if you incorrectly use the name of the file you are writing to instead of the file object returned by the open() function.

You can solve this error by calling the write() method on the file object, which will have the variable name defined after as in your with open statement.

For further reading on errors involving reading or writing to files in Python, go to the article: How to Solve Python ValueError: I/O operation on closed file.


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!