ERROR 程序出错,错误原因:'bytes' object has no attribute 'read'

使用json解析数据时,通常遇到这里就会出现问题'bytes' object has no attribute 'read',这是由于使用的json内置函数不同,一个是load另一个是loads。

import urllib.request
import json

response = urllib.request.urlopen('http://www.reddit.com/r/all/top/.json').read()
jsonResponse = json.load(response)

for child in jsonResponse['data']['children']:
    print (child['data']['title'])

通常解决方式有两种,一种是更改函数为loads,另一种是更改编码格式为utf8

第一种解决方式:

jsonResponse = json.loads(response.decode('utf-8'))

第二种解决方式

使用json.loads()而不是json.load()

内容参考:https://stackoverflow.com/questions/6541767/python-urllib-error-attributeerror-bytes-object-has-no-attribute-read

原文地址:https://www.cnblogs.com/sanduo1314/p/7668144.html