python - 使用 python 读取包含 json 数据的文件会抛出一个我无法识别的错误

标签 python json

我有以下名为 json.txt 的 json 文件,其中包含以下数据,

{"id":99903727,"nickname":"TEST_MLA_OFF","registration_date":"2010-12-03T14:19:33.000-04:00","country_id":"AR","user_type":"normal","logo":null,"points":0,"site_id":"MLA","permalink":"http://perfil.mercadolibre.com.ar/TEST_MLA_OFF","seller_reputation":{"level_id":null,"power_seller_status":null,"transactions":{"period":"12 months","total":25,"completed":25,"canceled":0,"ratings":{"positive":0,"negative":0,"neutral":1}}},"status":{"site_status":"deactive"}}

我是用wget得到的。我尝试使用以下 python 代码用 python 加载 json 数据,

json_data = json.load('json.txt')
data = json.load(json_data)
json_data.close()

print data

但是会抛出以下错误,

Traceback (most recent call last):
  File "json-example.py", line 28, in <module>
    main()
  File "json-example.py", line 21, in main
    json_data = json.load('json.txt')
  File "/opt/sage-4.6.2-linux-64bit-ubuntu_8.04.4_lts-x86_64-Linux/local/lib/python/json/__init__.py", line 264, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

我无法通过谷歌搜索错误的原因。

最好的问候。

最佳答案

更好的做法是使用 with 语句。

with open('json.txt', 'r') as json_file:
    data = json.load(json_file)

这确保文件在没有 你担心它。

关于python - 使用 python 读取包含 json 数据的文件会抛出一个我无法识别的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10288752/

相关文章:

python - SCons:如何在构建了一些目标后生成依赖项?

Python tkinter 无法在 crontab 上工作

iphone - Google map http 请求不起作用

.net - ASP .NET - JsonIgnore 似乎不起作用

php - 使用 PHP 进行 MySQL 查询的 JSONArray 不适用于复杂的查询

python - 如何从 scikit-learn DecisionTreeClassifier 获取信息增益?

python - Numpy 数组 : concatenate arrays and integers

java - 为什么我需要在Java程序中创建一个类?

javascript - 如何通过 ID 从数组中过滤 json 对象并传递给 recyclerview

javascript - 我如何开始使用 C# 和 MVC 创建这个 javascript 结构?