- Python Attributeerror: ‘str’ object has no attribute ‘read’
- 1. Calling read on a string object
- 2. Passing a string to json.load()
- 3. Calling read on urllib module
- Conclusion
- Take your skills to the next level ⚡️
- About
- Search
- AttributeError: ‘str’ object has no attribute ‘read’ ( Solved )
- Causes of attributeerror: ‘str’ object has no attribute ‘read’
- Case 1: Using read() method on filename
- Case 2: Using json.load() method
- Conclusion
- Join our list
- How to Solve Python AttributeError: ‘str’ object has no attribute ‘read’
- Table of contents
- AttributeError: ‘str’ object has no attribute ‘read’
- Example: Using json.load()
- Solution
- Summary
- Share this:
Python Attributeerror: ‘str’ object has no attribute ‘read’
The error Attributeerror: ‘str’ object has no attribute ‘read’ usually occurs when you are trying to read the content of a file in Python.
The stack trace of this error is as follows:
The read() function is a part of the built-in io module that’s used to read the content of a file. Calling the function from a string will cause this error.
The following examples show when this error occurs and how you can resolve it.
1. Calling read on a string object
Suppose you try to read the content of a file as follows:
Because the file_location variable is a string, calling the read() function will cause the error.
To fix this, you need to open the file first, then call the read() from the returned file object:
You don’t receive an error because the read() function is being called from the file object instead of the string file_location .
2. Passing a string to json.load()
The json.load() method in Python is used to read the content of a JSON file, but you still need to open the file first with open() .
Suppose you have a JSON file named data.json and you load it as follows:
You’ll get the same ‘str’ object has no attribute ‘read’ error.
To avoid the error, you need to open() the file first like this:
If you already have a JSON string, then use json.loads() to decode that string:
The json.load() method is used to decode a file content into a JSON object, while json.loads() decode a string into a JSON object.
3. Calling read on urllib module
This error may occur when you mistakenly call the read() function from a url string when using the urllib module.
Suppose you try to read the content of a website as follows:
The correct way to read a website’s content is to first open the url with urllib.request.urlopen() like this:
Conclusion
To conclude, the error Attributeerror: 'str' object has no attribute 'read' happens when the read() function is called from a string instead of a file object.
Most likely, you’ve misunderstood how to access and read a file object, such as when calling json.load() or reading from a URL. The examples above should help you fix this error.
I hope this article was helpful. Happy coding! 😉
Take your skills to the next level ⚡️
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
AttributeError: ‘str’ object has no attribute ‘read’ ( Solved )
The error attributeerror: ‘str’ object has no attribute ‘read’ occurs when you try to read the string file from the filename instead of the file object. If you have a file that contains JSON response and you use the json.load() method then you will also get the ‘str’ object has no attribute ‘read’ error.
In this entire tutorial, you will know how to solve this attributeError.
Causes of attributeerror: ‘str’ object has no attribute ‘read’
In most of the cases ‘str,’ object has no attribute ‘read’ error comes due to the two cases. You will know each case with its solution in this section.
Case 1: Using read() method on filename
Suppose you have a file with the name “text_file.txt” and you want to read and display it on the screen. The first step is to open the filename using the file stream and then read the file. Most of the developers instead of using the file object then call the read() method on the filename.
Look at the example given below. You will get the error ‘str’ object has no attribute ‘read’ error when you will run it.
In the above example, you can see I am calling the read() method using the filename(text_file) not on the file object(f). Thats why you are getting the error. You will not get the attributeError when you will call the read() method on the file object.
Output
Case 2: Using json.load() method
The other case when you will get the attributeerror: ‘str’ object has no attribute ‘read’ error is when you are using the json.load() while parsing the json response.
Output
The solution for the above case is that you have to use the json.loads() method to read the JSON response from the string type. Now You will not get the error.
You have to first read the JSON file before parsing the JSON response using the json.load() method. It is only for that case when you have a JSON response saved on the file.
Conclusion
The attributeerror: ‘str’ object has no attribute ‘read’ error is mostly due to not properly calling the read() method. The read() method must be called using the file object, not the filename.
The above method will solve the error you are getting due to the above cases.
I hope you have liked this tutorial. Still, if you have any doubts then you can contact us for more information.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
How to Solve Python AttributeError: ‘str’ object has no attribute ‘read’
This error typically occurs when you try to read the string pointing to the path of a file instead of a file object. To solve this error, you should use the appropriate method for reading the path of a file or reading a file object.
Generally, when reading in an object using a function, check to see what data type the function expects in its documentation.
This tutorial will go through the error in detail and solve it with code examples.
Table of contents
AttributeError: ‘str’ object has no attribute ‘read’
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 ‘read’” tells us that the string object does not have the attribute read(). The read() method belongs to the File data type and returns the specified number of bytes from the file. The syntax of the read method is as follows:
Let’s look at an example of using the read() method to read a file. The text file is ‘test.txt’ and has the following contents:
f = open('test.txt', 'r') print(type(f)) print(f.read())
The open() function opens a file and returns it as a file object. The parameter ‘r’ sets the function to read. We also print the type of f object to verify it is a file object. Let’s run the code to see the result:
TextIOWrapper object is a text stream that allows us to access the file’s contents as a list of strings.
Let’s see what happens when we try to call read() on a string representing the filename:
f = 'test.txt' print(type(f)) print(f.read())
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 1 f = 'test.txt' 2 print(type(f)) ----> 3 print(f.read()) AttributeError: 'str' object has no attribute 'read'
We raise the AttributeError because the read() method is only suitable for File objects. We cannot read a file by calling read() on the filename string.
Example: Using json.load()
The error commonly occurs when using the json library to read a JSON string instead of a JSON file object. There are two different methods in the json library:
- json.load() : Deserializes a text or binary file containing a JSON document to a Python object
- json.loads() : Deserializes a str, bytes, or bytearray instance containing a JSON document to a Python object
If you have a JSON string, you must use json.loads() if you use json.load() instead, you will raise the AttributeError.
Let’s look at an example where we want to make an HTTP POST request to httpbin. We will read a string into the program using open() and create a JSON payload to post to the specified URL.
The text file star_wars.txt contains the following dictionary:
The code to load and POST the payload is as follows:
import requests import json url = "https://httpbin.org/post" headers = < 'Content-Type': 'application/json', 'Accept': 'application/json' >infile = open('star_wars.txt', 'r') string = infile.readline() payload = json.load(string) response = requests.post(url, json=payload, no sheaders=headers) print("Status code: ", response.status_code) print("Response as JSON: ", response.json())
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 10 string = infile.readline() 11 ---> 12 payload = json.load(string) 13 14 x = request.post(url, json=payload, params=params, headers=headers) ~/opt/anaconda3/lib/python3.8/json/__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 291 kwarg; otherwise ``JSONDecoder`` is used. 292 """ --> 293 return loads(fp.read(), 294 cls=cls, object_hook=object_hook, 295 parse_float=parse_float, parse_int=parse_int, AttributeError: 'str' object has no attribute 'read'
The error occurs because the json.load() method expects a File object as a parameter but instead receives a string.
Solution
We need to use json.loads() to solve this error. Let’s look at the revised code:
import requests import json url = "https://httpbin.org/post" headers = < 'Content-Type': 'application/json', 'Accept': 'application/json' >infile = open('star_wars.txt', 'r') string = infile.readline() payload = json.loads(string) response = requests.post(url, json=payload, headers=headers) print("Status code: ", response.status_code) print("Response as JSON: ", response.json())
Let’s run the code to get the result:
Status code: 200 Response as JSON: , 'data': '', 'files': <>, 'form': <>, 'headers': , 'json': , 'origin': '90.206.95.191', 'url': 'https://httpbin.org/post?priority=normal'>
The status code 200 tells us we successfully made the HTTP request and retrieved the response.
Summary
Congratulations on reading to the end of this tutorial! The AttributeError: ‘str’ object has no attribute ‘read’ occurs when you call the read() method on a string object. You may encounter this when using the json library as there are two distinct methods load() for File objects and loads() string and byte objects. Ensure that you use the json.loads() method when you want to access the contents JSON string.
For further reading on AttributeErrors, go to the articles:
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!
Share this: