python写一个通讯录step by step V2.0
引用知识
-
list + dict用于临时存储用户数据信息
-
cPickle用于格式化文件存取
-
依旧使用file来进行文件的存储
解决问题
1、操刀开始去做
原始代码 实现功能(可做模板)
1、判断输入内容是否在给出的menu目录内,在的话,返回对应结果,不在就报错
2、调用os模块的exit功能
3、字典配合循环加上函数实现switch的功能
#!/usr/bin/env python #coding:utf8 #Author:zhuima #Date:2015-03-22 #Version:0.1 #Function:display a list and add date # 导入模块 import os def menu(): '''设置munu目录,提供给用户的操作接口 ''' print ''' 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program ''' op = raw_input('Please select one >>> ') return op def txl_exit(): ''' 退出程序 ''' os._exit(0) def txl_error(): ''' 当用户输出选项不在定义的选项内的时候,报错''' print print 'Unkonw options,Please try again!' # 定义dict,配合函数实现switch功能 ops = { # '1':txl_add, # '2':txl_dis, # '3':txl_update, # '4':txl_del, # '5':txl_sort, '0':txl_exit, } def main(): '''主程序 ''' while True: op = menu() ops.get(op,txl_error)() if __name__ == '__main__': main()
2、添加用户
思路
默认定义一个空list,然后嵌套dict来实现临时存储功能
-
1、添加的代码
# 导入模块 import os txl = [] .... def txl_add(): '''添加用户''' name = raw_input('Please Enter Your Name >>> ') age = raw_input('Please Enter Your Age >>> ') gender = raw_input('Please Enter Your Gender >>> ') tel = raw_input('Please Enter Your Tel >>> ') txl.append({'name':name,'age':age,'gender':gender,'tel':tel}) def txl_disp(): '''显示原始的txl列表 ''' print txl ..... ops = { '1':txl_add, '2':txl_disp, # '3':txl_update, # '4':txl_del, # '5':txl_sort, '0':txl_exit, }
-
2、测试结果
[root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 [] 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 1 Please Enter Your Name >>> zhuima Please Enter Your Age >>> 28 Please Enter Your Gender >>> f Please Enter Your Tel >>> 10086 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 [{'gender': 'f', 'age': '28', 'tel': '10086', 'name': 'zhuima'}] 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 0
-
3、完整代码块
-
3、格式化输出
格式化输出,使用字典
格式化输出:print "%(name)s\t%(age)s" % dict
-
1、添加代码片段
def txl_disp(): '''显示原始的txl列表 ''' print "name\tage\tgender\ttel" print "-----------------------" for x in txl: print "%(name)s\t%(age)s\t%(gender)s\t%(tel)s" % x
-
2、测试结果
[root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 1 Please Enter Your Name >>> zhuima Please Enter Your Age >>> 28 Please Enter Your Gender >>> f Please Enter Your Tel >>> 10086 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 1 Please Enter Your Name >>> nick Please Enter Your Age >>> 25 Please Enter Your Gender >>> m Please Enter Your Tel >>> 10010 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 1 Please Enter Your Name >>> kale Please Enter Your Age >>> 33 Please Enter Your Gender >>> f Please Enter Your Tel >>> 10011 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 28 f 10086 nick 25 m 10010 kale 33 f 10011 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 0
-
3、完整代码
-
4、文件写入与读取
思路:
引入cPickle概念,cPickle对文件进行读取与存入的格式化操作,
cPickle的loads功能(从文件中读取文件,保证原有格式)和dumps(把相关格式的对象文件存放到文件中)功能
-
1、添加代码块
# 导入模块 import os import cPickle # 定义数据库文件名 fname = 'contact.db' txl = [] ... def txl_add(): '''添加用户''' .... #调用txl_save()模块 txl_save() def txl_disp(): '''显示原始的txl列表 做了二次调整,如果txl为空,则打印木有文件存在,如果txl不为空 则打印出数据信息''' if len(txl) > 0: print "name\tage\tgender\ttel" print '----------------------------' for x in txl: print "%(name)s\t%(age)s\t%(gender)s\t%(tel)s" % x else: print print ">>> This is a empty file,There is no infomation! >>>" def txl_save(): '''使用cPickle进行列表到字符串的转换 然后写入文件 ''' s = cPickle.dumps(txl) fp = file(fname,'w') fp.write(s) fp.close() def txl_load(): '''从文件读取信息,然后使用cPickle进行字符串到列表的转换''' if os.path.exists(fname): fp = file(fname) s = fp.read() fp.close() txl.extend(cPickle.loads(s))
-
2、写入测试结果
[root@mysql01 day0330]# ls test.py v2_1.py v2.py [root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 >>> This is a empty file,There is no infomation! >>> 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 1 Please Enter Your Name >>> zhuima Please Enter Your Age >>> 25 Please Enter Your Gender >>> f Please Enter Your Tel >>> 10086 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 25 f 10086 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 1 Please Enter Your Name >>> nick Please Enter Your Age >>> 22 Please Enter Your Gender >>> m Please Enter Your Tel >>> 10010 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 25 f 10086 nick 22 m 10010 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 0 [root@mysql01 day0330]# ls contact.db test.py v2_1.py v2.py
-
3、读取测试结果
[root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 25 f 10086 nick 22 m 10010 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 0 [root@mysql01 day0330]#
-
4、完整代码
-
5、删除用户
思路:
根据用户名来进行数据的删除
先来看一个演示
-
案例演示如何删除嵌套列表字典
In [6]: s Out[6]: [{'age': 25, 'name': 'zhuima'}, {'age': 33, 'name': 'nick'}] #第一个思路就是要使用del来进行字典的删除,但是针对嵌套不生效 In [7]: for x in s: if x['name'] == 'zhuima': del x ...: print s ...: [{'age': 25, 'name': 'zhuima'}, {'age': 33, 'name': 'nick'}] # 后来使用列表的remove来进行删除,成功 In [10]: for x in s: if x['name'] == 'zhuima': s.remove(x) ....: In [11]: s Out[11]: [{'age': 33, 'name': 'nick'}]
-
1、代码片段
def txl_del(): '''根据用户名进行删除用户相应的信息,并进行数据存储,如果用户不输人该如何''' name = raw_input('Please Enter Your Want To Delete name >>> ') for line in txl: if line['name'] == name: txl.remove(line) break #最后记得调用存入的函数,要不然删除仅针对当前会话,没有写入文件 txl_save()
-
2、测试效果
[root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 25 f 10086 nick 22 m 10010 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 4 Please Enter Your Want To Delete name >>> nick 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 25 f 10086 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 0 [root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 25 f 10086 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>>
-
3、完整代码
-
6、根据用户输入自定义排序
思路:
根据用户的选择进行排序操作
引入功能,就是lambda txl.sort(key=lambda x : x[op])
-
1、代码片段
def txl_sort(): '''根据用户的输入对数据进行排序,用到了lambda函数,有bug的,应该提供一个默认值出来进行排序''' op = raw_input('Order By [name | age | gender | tel ] Display >>> ') txl.sort(key=lambda x : x[op]) txl_disp()
-
2、测试结果
[root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- zhuima 25 f 10086 nick 22 m 10011 kale 29 f 10093 tony 18 m 10010 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 5 Order By [name | age | gender | tel ] Display >>> name name age gender tel ---------------------------- kale 29 f 10093 nick 22 m 10011 tony 18 m 10010 zhuima 25 f 10086 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 5 Order By [name | age | gender | tel ] Display >>> age name age gender tel ---------------------------- tony 18 m 10010 nick 22 m 10011 zhuima 25 f 10086 kale 29 f 10093 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>>
-
3、完整代码
-
7、更新数据
思路:
方法一: 使用字典重新赋值即可实现更新(本案例演示采用的第一种方式)方法二: 根据索引找到对应的用户所在的dict,然后对整个dict进行更新
-
根据索引找到对应的dict进行更新的案例演示
In [38]: s Out[38]: [{'age': 44, 'name': 'zhuima'}, {'age': 33, 'name': 'nick'}] In [39]: for x in s: ....: if x['name'] == 'zhuima': ....: s[s.index(x)] = {'name':'zhuima521','age':28} ....: In [40]: s Out[40]: [{'age': 28, 'name': 'zhuima521'}, {'age': 33, 'name': 'nick'}] In [41]:
-
1、代码片段
def txl_update(status=True): '''根据用户名对该用户的相关数据进行更新操作,用户名不可变,如果选项不更新,则保留默认值,否则更新''' txl_disp() name = raw_input('Select One Update By Name >>> ') for line in txl: if line['name'] == name: status = False old_age = line['age'] old_gender = line['gender'] old_tel = line['tel'] age = raw_input('Please Enter Your Age for %s >>> ' % name) gender = raw_input('Please Enter Your Gender for %s >>> ' % name) tel = raw_input('Please Enter Your Tel for %s >>> ' % name) if len(age) == 0: line['age'] = old_age else: line['age'] = age if len(gender) == 0: line['gender'] = old_gender else: line['gender'] = gender if len(tel) == 0: line['tel'] = old_tel else: line['tel'] = tel break if status: print "Unkonw User,Try Again!" txl_save()
-
2、测试结果
[root@mysql01 day0330]# python v2_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- fuck 30 m 90000 kale 33 f 10093 tony 18 m 10010 zhuima 25 f 10086 max 32 f 20000 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 3 name age gender tel ---------------------------- fuck 30 m 90000 kale 33 f 10093 tony 18 m 10010 zhuima 25 f 10086 max 32 f 20000 Select One Update By Name >>> kale Please Enter Your Age for kale >>> Please Enter Your Gender for kale >>> Please Enter Your Tel for kale >>> 99999 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name age gender tel ---------------------------- fuck 30 m 90000 kale 33 f 99999 tony 18 m 10010 zhuima 25 f 10086 max 32 f 20000 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 3 name age gender tel ---------------------------- fuck 30 m 90000 kale 33 f 99999 tony 18 m 10010 zhuima 25 f 10086 max 32 f 20000 Select One Update By Name >>> min Unkonw User,Try Again! 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>>
-
3、完整代码
-
总结
至此,我们使用dict完成了数据库的增、删、改、查、排序等操作
完整代码
#!/usr/bin/env python #coding:utf8 #Author:zhuima #Date:2015-03-22 #Version:0.1 #Function:display a list and add date # 导入模块 import os import cPickle fname = 'contact.db' txl = [] def menu(): '''设置munu目录,提供给用户的操作接口 ''' print ''' 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program ''' op = raw_input('Please select one >>> ') return op def txl_add(): '''添加用户''' name = raw_input('Please Enter Your Name >>> ') age = raw_input('Please Enter Your Age >>> ') gender = raw_input('Please Enter Your Gender >>> ') tel = raw_input('Please Enter Your Tel >>> ') txl.append({'name':name,'age':age,'gender':gender,'tel':tel}) txl_save() def txl_disp(): '''显示原始的txl列表 ''' if len(txl) > 0: print "name\tage\tgender\ttel" print '----------------------------' for x in txl: print "%(name)s\t%(age)s\t%(gender)s\t%(tel)s" % x else: print print ">>> This is a empty file,There is no infomation! >>>" def txl_save(): '''对数据进行写操作,写之前进行格式转换''' s = cPickle.dumps(txl) fp = file(fname,'w') fp.write(s) fp.close() def txl_load(): '''对文件进行读取,如果文件存在的情况下 ''' if os.path.exists(fname): fp = file(fname) s = fp.read() fp.close() txl.extend(cPickle.loads(s)) def txl_update(status=True): '''根据用户名对该用户的相关数据进行更新操作,用户名不可变,如果选项不更新,则保留默认值,否则更新''' txl_disp() name = raw_input('Select One Update By Name >>> ') for line in txl: if line['name'] == name: status = False old_age = line['age'] old_gender = line['gender'] old_tel = line['tel'] age = raw_input('Please Enter Your Age for %s >>> ' % name) gender = raw_input('Please Enter Your Gender for %s >>> ' % name) tel = raw_input('Please Enter Your Tel for %s >>> ' % name) if len(age) == 0: line['age'] = old_age else: line['age'] = age if len(gender) == 0: line['gender'] = old_gender else: line['gender'] = gender if len(tel) == 0: line['tel'] = old_tel else: line['tel'] = tel break if status: print "Unkonw User,Try Again!" txl_save() def txl_del(): '''根据用户名进行删除用户相应的信息,并进行数据存储''' name = raw_input('Please Enter Your Want To Delete name >>> ') for line in txl: if line['name'] == name: txl.remove(line) break txl_save() def txl_sort(): '''根据用户的输入对数据进行排序,用到了lambda函数 ''' op = raw_input('Order By [name | age | gender | tel ] Display >>> ') txl.sort(key=lambda x : x[op]) txl_disp() def txl_exit(): ''' 退出程序 ''' os._exit(0) def txl_error(): ''' 当用户输出选项不在定义的选项内的时候,报错''' print print 'Unkonw options,Please try again!' # 定义dict,配合函数实现switch功能 ops = { '1':txl_add, '2':txl_disp, '3':txl_update, '4':txl_del, '5':txl_sort, '0':txl_exit, } txl_load() def main(): '''主程序 ''' while True: op = menu() ops.get(op,txl_error)() if __name__ == '__main__': main()
本文转自lovelace521 51CTO博客,原文链接:http://blog.51cto.com/lovelace/1630275,如需转载请自行联系原作者