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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'str' object has no attribute 'read' #

The Python "AttributeError: 'str' object has no attribute 'read'" occurs when we call the read() method on a string (e.g. a filename) instead of a file object or use the json.load() method by mistake. To solve the error, call the read() method on the file object after opening the file.

attributeerror str object has no attribute read

Here is an example of how the error occurs.

main.py
file_name = 'example.txt' with open(file_name, encoding='utf-8') as f: # ⛔️ AttributeError: 'str' object has no attribute 'read' read_data = file_name.read() print(read_data)

We tried to call the read() method on the filename string instead of the file object which caused the error.

If you are reading from a file, make sure to call the read() method on the file object instead.

main.py
file_name = 'example.txt' with open(file_name, encoding='utf-8') as f: # ✅ calling read() on file object read_data = f.read() print(read_data)

Another common cause of the error is using the json.load() method when trying to parse a JSON string into a native Python object.

main.py
import json # ⛔️ AttributeError: 'str' object has no attribute 'read' result = json.load('{"name": "Alice"}')

The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.

If you are trying to parse a JSON string into a native Python object, use the json.loads (with s) method instead.

main.py
import json result = json.loads('{"name": "Alice"}') print(type(result)) # 👉️ <class 'dict'> print(result) # 👉️ {'name': 'Alice'}

We parsed the JSON string into a dictionary using the json.loads() method.

If you are trying to use the json.load() method to deserialize a file to a Python object, open the file and pass the file object to the json.load() method.

main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) print(my_data) # 👉️ {'name': 'Alice', 'age': 30}

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method. If you call the json.load() method with a string, it tries to call the read() method on the string.

If you are getting the error when using the urllib module, open the request before calling the read() method.

main.py
import urllib.request with urllib.request.urlopen('http://www.python.org/') as f: # 👇️ call read() here print(f.read())

A good way to start debugging is to print(dir(your_object)) and see what attributes a string has.

Here is an example of what printing the attributes of a string looks like.

main.py
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

If you pass a class to the dir() function, it returns a list of names of the class's attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: str object has no attribute error".

Since the str object doesn't implement a read() method, the error is caused.

Conclusion #

The Python "AttributeError: 'str' object has no attribute 'read'" occurs when we call the read() method on a string (e.g. a filename) instead of a file object or use the json.load() method by mistake. To solve the error, call the read() method on the file object after opening the file.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.