AttributeError(“’str’对象没有属性’read’”)

问题:AttributeError(“’str’对象没有属性’read’”)

在Python中,我得到一个错误:

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

给定python代码:

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)
    jsonofabitch = response.read ()

    return json.load (jsonofabitch)['data']['children']

此错误是什么意思,我怎么做导致此错误?

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)
    jsonofabitch = response.read ()

    return json.load (jsonofabitch)['data']['children']

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


回答 0

问题在于,对于json.load您,应该传递带有已read定义函数的对象之类的文件。因此,您可以使用json.load(response)json.loads(response.read())

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()).


回答 1

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

这就是说的意思:有人试图.read在给它的对象上找到一个属性,然后给它一个类型的对象str(即,给它一个字符串)。

错误发生在这里:

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

好吧,您不在read任何地方寻找,因此它必须在json.load您调用的函数中发生(如完整的回溯所示)。这是因为json.load正在尝试提供给.read您的东西,但是却给了它jsonofabitch,该东西当前命名为字符串(通过调用.read来创建response)。

解决方案:不要.read自欺欺人。函数将执行此操作,并希望您response直接给它以使其可以执行操作。

您也可以通过阅读功能的内置Python文档(try help(json.load)或整个模块(try help(json))),或通过查看http://docs.python.org上这些功能的文档来解决此问题。

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 (jsonofabitch)['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 jsonofabitch, 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 .


回答 2

如果收到这样的python错误:

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

您可能通过用字符串覆盖对象意外地中毒了对象。

如何用几行代码在python中重现此错误:

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

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

运行它,打印:

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

但是更改变量名的名称,它可以正常工作:

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

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

当您尝试在字符串中运行方法时,导致此错误。字符串有几种方法,但是您没有调用。因此,停止尝试调用String未定义的方法,并开始寻找在何处毒害了对象。

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.


回答 3

好的,这是旧线程了。我有一个相同的问题,我的问题是我用了json.load而不是json.loads

这样,json加载任何类型的字典都没有问题。

官方文件

json.load-使用此转换表将fp(支持.read()的文本文件或包含JSON文档的二进制文件)反序列化为Python对象。

json.loads-使用此转换表将s(包含JSON文档的str,字节或字节数组实例)反序列化为Python对象。

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.


回答 4

您需要先打开文件。这不起作用:

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

但这有效:

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

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)