首页 > 解决方案 > AttributeError: '_io.TextIOWrapper' 对象没有属性 'load'

问题描述

通过以下方式在python中读取json文件会出现错误。

json=open('file.json')

data = json.load(json)   OR

with open("data_file.json", "r") as read_file:
    data = json.load(read_file)

两者都给出AttributeError: '_io.TextIOWrapper' object has no attribute 'load'。这是什么原因?

标签: jsonpython-3.x

解决方案


你不应该称你是可变的json。这导致了错误。

执行以下操作:

import json

not_json = open('file.json')
data = json.load(not_json)

甚至更好:

with open('file.json') as input_file:
    data = json.load(input_file)

[编辑]

为了解决下面的评论,当您声明如下内容时:

import json

json = 2

这个词json现在指向一个数字,并且您丢失了导入包的名称。除非您在不同的范围内(例如在函数内)声明它,否则这是正确的。

最佳实践:尽量避免以内置名称、已知包等命名变量/函数/类等(例如list = 2; list([1,2,3]):)


推荐阅读