在 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)
jsonStr = response.read()
return json.load(jsonStr)['data']['children']
这个错误是什么意思,我做了什么导致它?
原文由 RobinJ 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是,对于
json.load
你应该传递一个像对象一样的文件,其中定义了read
函数。所以要么你使用json.load(response)
要么json.loads(response.read())
。