我想制作一个从文本(字典)中读取信息的程序。如果key不存在,则程序应添加此key,并且还必须逐行将keyvalue添加到文本文件中。我做了些什么,但是在阅读部分时,有问题说列表索引超出范围。有人可以帮忙吗?
with open('text.txt','r') as file:
x={}
for line in file:
key = line.rstrip().split(':')[0]
keyvalue = line.rstrip().split(':')[1]
x[key]=keyvalue
while True:
name = input('whose hobby you wanna learn?:')
if name in x:
print('Name found')
print("%s's hobby is %s" %(name,x[name]))
else:
print('i do not know',name)
answer = input('do you wanna add this person?(yes or no)')
if answer == ('yes'):
new_user= input('type the name of new person:')
new_user_hobby = input('type the hobby of that person:')
x[new_user] = new_user_hobby
with open('text.txt','a') as file:
file.write('\n')
file.write(new_user)
file.write(':')
file.write(new_user_hobby)
print('person created successfully!')
使用JSON。
{
"key1": "value1",
"key2": "value2"
}
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)
如果你运行它,输入key3
,然后输入yes
,然后value3
和data.json
文件将是这样的:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句