Use JSON.
File data.json
{
"key1": "value1",
"key2": "value2"
}
File main.py
import json
with open("data.json", "r") as jsonfile:
data = json.load(jsonfile)
key = input("enter key: ")
if key in data:
print("key %s has value %s" % (key, data[key]))
else:
add = input("key %s was not found in the data; do you want to add it ? " % key)
if add:
value = input("enter value for key %s : " % key)
data[key] = value
jsonfile.close()
with open("data.json", "w") as jsonfile:
json.dump(jsonfile, data)
If you run it, enter key3
, then enter yes
, then value3
, and the data.json
file will be like this:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…