关于python:AttributeError(“’str’对象没有属性’read’”))

AttributeError(“'str' object has no attribute 'read'”)

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

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

给定python代码:

1
2
3
4
5
6
7
8
9
10
11
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']

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


问题是对于json.load,您应该传递一个定义了read函数的类似object的文件。因此,您可以使用json.load(response)json.loads(response.read())


如果收到这样的python错误:

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

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

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

1
2
3
4
5
6
#!/usr/bin/env python
import json
def foobar(json):
    msg = json.loads(json)

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

运行它,打印:

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

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

1
2
3
4
5
6
#!/usr/bin/env python
import json
def foobar(jsonstring):
    msg = json.loads(jsonstring)

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

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


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

这就是它的意思:某东西试图在给它的对象上找到一个.read属性,并且给了它一个str类型的对象(即,给了它一个字符串)。

错误发生在这里:

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

好吧,您并没有在任何地方寻找read,因此它必须在您调用的json.load函数中发生(如完整的追溯所示)。这是因为json.load试图.read给您的东西,但给了它jsonofabitch,它当前为一个字符串命名(由您在response上调用.read创建的)。

解决方案:不要自己打电话给.read;该函数将执行此操作,并希望您直接给它response以便它可以执行此操作。

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