我正在一个项目中,我正在使用Dictionary作为存储对象的数据库。但是,我无法进入文本文件中的Dictionary,并且无法在其中添加更多项。
我的文本文件:
a = {1:2,2:1}
我的代码:我无法找到办法在该词典中附加更多项目。
仅举一个例子,您可以使用python字典做更多的事情。请参阅此处以了解更多:https://www.w3schools.com/python/python_dictionaries.asp
a = {
"Index": 1,
"Model": "2019",
1: 2,
2:1
}
import json
with open('file.txt', 'w') as file: # Writing to file here
file.write(json.dumps(a))
file.close()
with open('file.txt') as file: # Reading the file here
data = json.load(file)
print (data)
file.close()
data["type"] = "dictionary" # Adding item to dictionary
print(data)
添加项目前的输出:
{'Index': 1, 'Model': '2019', '1': 2, '2': 1}
添加项目后的输出:
{'Index': 1, 'Model': '2019', '1': 2, '2': 1, 'type': 'dictionary'}