问题描述
我正在尝试创建一个地址簿,但是有一个问题:
- 启动程序并添加键(联系人)时,添加后无法将其删除。
- 只有重启程序(退出并启动)后,我才能删除按键(联系人)。
- 当我尝试删除一个键(重新启动后)时,程序会删除所有键。
从命令行运行测试程序的示例:
[user@arch Python]$ python3 addres_book.py
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: l
{}
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: a
{}
Enter the name: alex
Enter the number: 122
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: r
{'alex': 122}
Enter the name of contact: alex
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: l
{'alex': 122}
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: a
{'alex': 122}
Enter the name: trump
Enter the number: 134
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: q
[user@arch Python]$ python3 addres_book.py
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: l
{'alex': 122,'trump': 134}
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: r
{'alex': 122,'trump': 134}
Enter the name of contact: trump
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
Enter function: l
{}
What to do?:
l - full list
a - add a contact
r - remove contact
s - search contact
q - quit
程序代码:
import os
import pickle
addressbook = {}
home = os.environ['HOME']
path = home + '/.local/share/addressbook'
addressbookfile = path + '/' + 'addressbook.data'
if not os.path.exists(path):
os.mkdir(path)
while True:
print("What to do?: ")
print("l - full list")
print("a - add a contact")
print("r - remove contact")
print("s - search contact")
print("q - quit")
answer = str(input("Enter function: "))
if answer == 'l':
f = open(addressbookfile,'rb')
storedfile = pickle.load(f)
print(storedfile)
elif answer == 'a':
f = open(addressbookfile,'rb')
storedfile = pickle.load(f)
print(storedfile)
name = str(input("Enter the name: "))
number = int(input("Enter the number: "))
addressbook[name] = number
f = open(addressbookfile,'wb')
pickle.dump(addressbook,f)
f.close()
elif answer == 'r':
f = open(addressbookfile,'rb')
storedfile = pickle.load(f)
print(storedfile)
f = open(addressbookfile,'rb')
storedfile = pickle.load(f)
delanswer = str(input("Enter the name of contact: "))
del storedfile[delanswer]
f = open(addressbookfile,f)
f.close()
elif answer == 's':
f = open(addressbookfile,'rb')
storedfile = pickle.load(f)
search = input("Enter the data: ")
searchresult = storedfile.get(search)
print(searchresult)
elif answer == 'q':
break
else:
continue
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)