我想做一个程序,从文本(字典)读取信息。如果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
文件data.json
{
"key1": "value1",
"key2": "value2"
}
文件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)
如果你运行它,输入key3
,然后输入yes
,然后输入value3
,data.json
文件将是这样的:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
请尝试更改这些行
key = line.rstrip().split(':')[0]
keyvalue = line.rstrip().split(':')[1]
key, keyvalue = line.strip().split(':')
看起来您有空行或没有:
的行。
尝试使用if-else:
with open('text.txt','r') as file:
x={}
for line in file:
split_line = line.rstrip().split(':')
if len(split_line) == 2:
key = split_line[0]
keyvalue = split_line[1]
x[key]=keyvalue