如何使用 json.load 将信息从 txt 保存到字典

How to use json.load to save info from a txt to a dictionary

我正在尝试在字典上使用 json.load;但是,我收到此错误:

Traceback (most recent call last):
File "C:\Python34\Main.py", line 91, in
main()
File "C:\Python34\Main.py", line 87, in main
match_histories = json.load("match_histories.txt")
File "C:\Python34\lib\json__init__.py", line 265, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

这是我的代码(我先导入 json):

import json
match_histories = {}
match_histories["age"] = 25
json.dump(match_histories, "match_histories.txt")
match_histories = json.load(open("match_histories.txt"))

嗯,现在我收到转储错误:

Traceback (most recent call last):
File "C:\Python34\Main.py", line 91, in
main()
File "C:\Python34\Main.py", line 82, in main
match_histories=get_match_histories(challenger_Ids)
File "C:\Python34\Main.py", line 50, in get_match_histories
json.dump(match_histories, "match_histories.txt")
File "C:\Python34\lib\json__init__.py", line 179, in dump
fp.write(chunk)
AttributeError: 'str' object has no attribute 'write'

尝试了建议后,我将代码更改为

import json
match_histories = {}
match_histories["age"] = 25
with open("match_histories.txt") as match_file:
    match_histories = json.dump(match_histories, "match_histories.txt")
with open("match_histories.txt") as match_file:
    match_histories = json.load(match_file)

但我仍然收到错误

File "C:\Python34\lib\json__init__.py", line 179, in dump
fp.write(chunk)
AttributeError: 'str' object has no attribute 'write'

(抱歉,我是 python 和编程的新手)

AttributeError: 'str' object has no attribute 'read'

如您所见,它尝试在传递的对象上调用 read(),但您传递的是字符串对象而不是文件(或任何其他实现 read() 的对象)

json.load() 想要一个文件对象,而不是它的路径字符串,所以使用 open() 打开文件然后传递它,或者类似下面的代码:

with open('file.json') as json_file:    
    json_data = json.load(json_file)

如果您打开要写入的文件,您应该将 w 模式设置为 open(),例如 open('file.json', 'w')

来自docs

json.load(fp, ...)

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

你和 json.dump

有同样的问题

AttributeError: 'str' object has no attribute 'write'

json.dump(obj, ...) Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.

例子

import json
match_histories = {}
match_histories["age"] = 25

print 'Python dict is', match_histories

with open('match.json', 'w') as json_file:
    json.dump(match_histories, json_file)

with open('match.json', 'r') as json_file:
    match_histories = json.load(json_file)

print 'Python dict restored from JSON', match_histories

运行它

python jsontest.py

Python dict is {'age': 25}
Python dict restored from JSON {u'age': 25}

JSON

{"age": 25}