Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError("'str' object has no attribute 'read'")

In Python I'm getting an error:

Exception:  (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)

Given python code:

def getEntries (self, sub):
    url = 'http://www.reddit.com/'
    if (sub != ''):
        url += 'r/' + sub
    
    request = urllib2.Request (url + 
        '.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
    response = urllib2.urlopen (request)
    jsonStr = response.read()
    
    return json.load(jsonStr)['data']['children']

What does this error mean and what did I do to cause it?

like image 584
RobinJ Avatar asked Jun 24 '12 00:06

RobinJ


People also ask

How do I fix 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.

How do I fix AttributeError str object has no attribute append?

The Python "AttributeError: 'str' object has no attribute 'append'" occurs when we try to call the append() method on a string (e.g. a list element at specific index). To solve the error, call the append method on the list or use the addition (+) operator if concatenating strings.


6 Answers

The problem is that for json.load you should pass a file like object with a read function defined. So either you use json.load(response) or json.loads(response.read()).

like image 123
kosii Avatar answered Sep 23 '22 04:09

kosii


Ok, this is an old thread but. I had a same issue, my problem was I used json.load instead of json.loads

This way, json has no problem with loading any kind of dictionary.

Official documentation

json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

like image 30
JohnyMSF Avatar answered Sep 24 '22 04:09

JohnyMSF


You need to open the file first. This doesn't work:

json_file = json.load('test.json')

But this works:

f = open('test.json')
json_file = json.load(f)
like image 34
music_piano Avatar answered Sep 23 '22 04:09

music_piano


If you get a python error like this:

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

You probably poisoned your object accidentally by overwriting your object with a string.

How to reproduce this error in python with a few lines of code:

#!/usr/bin/env python
import json
def foobar(json):
    msg = json.loads(json)

foobar('{"batman": "yes"}')

Run it, which prints:

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

But change the name of the variablename, and it works fine:

#!/usr/bin/env python
import json
def foobar(jsonstring):
    msg = json.loads(jsonstring)

foobar('{"batman": "yes"}')

This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.

like image 23
Eric Leschinski Avatar answered Sep 24 '22 04:09

Eric Leschinski


AttributeError("'str' object has no attribute 'read'",)

This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).

The error occurred here:

json.load(jsonStr)['data']['children']

Well, you aren't looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonStr, which currently names a string (which you created by calling .read on the response).

Solution: don't call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.

You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .

like image 43
Karl Knechtel Avatar answered Sep 24 '22 04:09

Karl Knechtel


Instead of json.load() use json.loads() and it would work: ex:

import json
from json import dumps

strinjJson = '{"event_type": "affected_element_added"}'
data = json.loads(strinjJson)
print(data)
like image 25
Pallav Ghose Avatar answered Sep 23 '22 04:09

Pallav Ghose