学Python也有一阵子了,今天就做一个属于自己的简陋通讯录!
思路:利用字典可以存放通讯录,利用pickle可以将通讯录存在文件里,每次操作拿出,操作之后再存进文件
首先,创建一个字典保存一些信息到文件里:
import pickle
ab = {
'Jane': {
'tel': '15873403948',
'email': '3jd3di0@skdi.com'
},
'marry': {
'tel': '12834394939',
'email': '49jdi3idz@qq.com'
},
'james': {
'tel': '17783743847',
'email': 'saeiadji@sina.com'
}
}
with open('ab.pkl', 'wb') as f:
pickle.dump(ab, f)
f.close()
然后定义增加和修改函数,因为修改和增加方法
dict['newkey'] = 'newvalue'
一致
improt pickle
def add_cha():
with open('ab.pkl', 'rb') as f:
ab_file = pickle.load(f)
name = list(ab_file.keys())
print(name)
f.close()
with open('ab.pkl', 'wb') as s:
a = input('Enter name:')
b = input('Enter tel:')
c = input('Enter email:')
ab_file[a] = {'tel': b,
'email': c
}
print('Success!\n', list(ab_file.keys()))
pickle.dump(ab_file, s)
s.close()
之前写的是with open('ab.pkl', 'r') as f
此处出了一个报错write() argument must be str, not bytes
产生问题的原因是因为pickle存储方式默认是二进制方式
就是说也要以二进制方式打开
然后改为with open('ab.pkl', 'rb') as f
接着是查函数:
def sel():
with open('ab.pkl', 'rb') as f:
ab_file = pickle.load(f)
name = list(ab_file.keys())
print(name)
f.close()
while True:
a = input('Enter name:')
if a == 'quit':
break
if a in name:
print(ab_file[a])
else:
print('Adressbook doesn\'t have it!')
最后就是删除函数了:
def del_info():
with open('ab.pkl', 'rb') as f:
ab_file = pickle.load(f)
name = list(ab_file.keys())
print(name)
i = input('Enter name:')
if i in name:
del ab_file[i]
s = open('ab.pkl', 'wb')
pickle.dump(ab_file, s)
print('Success!')
s.close()
else:
print('Wrong name!')
f.close()
让我们来运行一下吧!
add_cha()
:
sel()
:We did it!!!
还有很多可以改进和优化的地方,希望大家可以留言或者联系我提出意见和不足
转载请注明出处
python自学技术互助扣扣群:670402334
网友评论