当前位置:Gxlcms > Python > Python编写电话薄实现增删改查

Python编写电话薄实现增删改查

时间:2021-07-01 10:21:17 帮助过:48人阅读

这篇文章主要为大家详细介绍了Python编写电话薄实现增删改查功能的相关资料,感兴趣的朋友可以参考一下

初学python,写一个小程序练习一下。主要功能就是增删改查的一些功能。主要用到的技术:字典的使用,pickle的使用,io文件操作。代码如下:

  1. import pickle
  2. #studentinfo = {'netboy': '15011038018',\
  3. # 'godboy': '15011235698'}
  4. studentinfo = {}
  5. FUNC_NUM = 5
  6. def write_file(value):
  7. file = open('student_info.txt', 'wb')
  8. file.truncate()
  9. pickle.dump(value, file, True)
  10. file.close
  11. def read_file():
  12. global studentinfo
  13. file = open('student_info.txt', 'rb')
  14. studentinfo = pickle.load(file)
  15. file.close()
  16. def search_student():
  17. global studentinfo
  18. name = input('please input student\'s name:')
  19. if name in studentinfo:
  20. print('name:%s phone:%s' % (name, studentinfo[name]))
  21. else:
  22. print('has no this body')
  23. def delete_student():
  24. global studentinfo
  25. name = input('please input student\'s name:')
  26. if name in studentinfo:
  27. studentinfo.pop(name)
  28. write_file(studentinfo)
  29. else:
  30. print('has no this body')
  31. def add_student():
  32. global studentinfo
  33. name = input('please input student\'s name:')
  34. phone = input('please input phone:')
  35. studentinfo[name] = phone
  36. write_file(studentinfo)
  37. def modifiy_student():
  38. global studentinfo
  39. name = input('please input student\'s name:')
  40. if name in studentinfo:
  41. phone = input('please input student\'s phone:')
  42. studentinfo[name] = phone
  43. else:
  44. print('has no this name')
  45. def show_all():
  46. global studentinfo
  47. for key, value in studentinfo.items():
  48. print('name:' + key + 'phone:' + value)
  49. func = {1 : search_student, \
  50. 2 : delete_student, \
  51. 3 : add_student, \
  52. 4 : modifiy_student, \
  53. 5 : show_all}
  54. def menu():
  55. print('-----------------------------------------------');
  56. print('1 search student:')
  57. print('2 delete student:')
  58. print('3 add student:')
  59. print('4 modifiy student:')
  60. print('5 show all student')
  61. print('6 exit')
  62. print('-----------------------------------------------');
  63. def init_data():
  64. global studentinfo
  65. file = open('student_info.txt', 'rb')
  66. studentinfo = pickle.load(file)
  67. #print(studentinfo)
  68. file.close()
  69. init_data()
  70. while True:
  71. menu()
  72. index = int(input())
  73. if index == FUNC_NUM + 1:
  74. exit()
  75. elif index < 1 or index > FUNC_NUM + 1:
  76. print('num is between 1-%d' % (FUNC_NUM + 1))
  77. continue
  78. #print(index)
  79. func[index]()

以上就是本文的全部内容,希望对大家学习Python程序设计有所帮助。

更多Python编写电话薄实现增删改查相关文章请关注PHP中文网!

人气教程排行