【问题标题】:Saving a dictionary to a file将字典保存到文件
【发布时间】:2017-07-14 01:20:03
【问题描述】:

我对 Python 很陌生,我正在尝试获取名为 python_diction 的字典的内容(位于一个较大的文件中)并将该数据保存到一个名为 python_diction_saved.json 的新文件中。我觉得我非常接近我目前收到的错误是 python_diction_saved.json 未定义。

任何帮助将不胜感激。

import json
f = open("python_diction.txt","w")
python_diction = {}
python_diction["items"] = []
python_diction["items"].append({"hello":1,"hi":2})
python_diction["items"].append({"hello":42,"hi":65})
python_diction["numbers"] = [1,2,3,5,7,8]
f.write(json.dumps(python_diction_saved.json))
f.close()

【问题讨论】:

  • python_diction_saved => python_diction
  • 太好了,解决了第一个回溯错误,但现在我得到另一个回溯错误......f.write(json.dumps(python_diction_saved.json)) AttributeError: 'dict' object没有属性“json”
  • 来吧:python_diction_saved.json => python_diction
  • 您还需要打开另一个名为"python_diction_saved.json"的文件
  • @Faibbus no,文件已经在"python_diction.txt"下打开。

标签: json python-2.7 file dictionary


【解决方案1】:

要将您的python_diction 写入名为python_diction_saved.json 的文件,您可以使用json.dump(避免自己编写):

import json
python_diction = {}
python_diction["items"] = []
python_diction["items"].append({"hello":1,"hi":2})
python_diction["items"].append({"hello":42,"hi":65})
python_diction["numbers"] = [1,2,3,5,7,8]

with open("python_diction_saved.json") as output_file:
    json.dump(python_diction, output_file)

【讨论】:

    猜你喜欢
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多