json - 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'
。这是什么原因?
解决方案
你不应该称你是可变的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])
:)
推荐阅读
- php - 使用 PDO 在 mysql 中插入数据的问题
- java - 如何在 Ant JunitLauncher 中将系统属性作为参数提供
- c++ - 在 C++ 中读取 .txt 文件
- javascript - 用户编辑文本区域后,重置/提交按钮将不起作用?
- jersey - 当响应来自异常映射器时如何绕过响应过滤器
- python - 使用 Openpyxl 将内容粘贴到 Excel 时如何跳过一个或多个单元格?
- php - Laravel 5.4 关系有很多不起作用
- r - 如何使用 rtweet 包收集过去 7 天内的推文?
- java - 线程的 Java 垃圾收集
- ios - 部署到 App Engine 时找不到 tsconfig.app.json