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

2024-04-27 03:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在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']

这个错误是什么意思?我是怎么造成的?


Tags: jsonurlreadobjectresponserequesttype错误
3条回答

如果出现这样的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'

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

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

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

此错误是在尝试在字符串中运行方法时导致的。String有一些方法,但不是您要调用的方法。因此,停止尝试调用字符串未定义的方法,并开始寻找中毒对象的位置。

问题是,对于json.load,应该传递一个定义了read函数的类文件对象。所以要么使用^{}要么使用^{}

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

这正是它所说的意思:某物试图在你给它的对象上找到一个.read属性,你给了它一个str类型的对象(即,你给了它一个字符串)。

此处发生错误:

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

好吧,您不需要在任何地方寻找read,所以它必须发生在您调用的json.load函数中(如完整的回溯所示)。这是因为json.load试图.read你给它的东西,但是你给了它jsonofabitch,它目前命名一个字符串(你通过在response上调用.read创建的)。

解决方案:不要自己调用.read;函数会这样做,并希望您直接给它response,以便它可以这样做。

您还可以通过阅读函数(tryhelp(json.load))或整个模块(tryhelp(json))的内置Python文档,或者通过检查这些函数在http://docs.python.org上的文档来了解这一点。

相关问题 更多 >