【问题标题】:reading a file with json data with python throw an error that I cannot identify使用 python 读取包含 json 数据的文件会引发我无法识别的错误
【发布时间】:2012-04-23 21:42:45
【问题描述】:

我有以下名为 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'

我在谷歌上找不到错误的原因。

最好的问候。

【问题讨论】:

    标签: python json


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      你需要给json.load一个文件流对象:

      json_file = open('json.txt')
      data = json.load(json_file)
      json_file.close()
      
      print data
      

      【讨论】:

      • 谢谢。就是这样。最好的问候。
      • 我在包含{"a":1,"b":2} json 对象的文件上尝试了相同的操作,但我得到了错误AttributeError: __exit__。任何帮助都会很有用。
      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2022-10-14
      • 2017-11-12
      • 2016-12-08
      • 2015-02-11
      • 2014-09-15
      • 1970-01-01
      相关资源
      最近更新 更多