还记得川川我吗?啊,不记得就伤我心了,点个赞加个关再走。
QQ:2835809579
白嫖党们,走起!
题目:
通讯录文件中存有若干联系人的信息,每个联系人的信息由姓名和电话号码组成。编写程序完成以下功能:输入姓名,若通讯录文件中存在,则将该联系人信息输出;若不存在,则输出“Not Found”。
代码:
#登录引导界面 txt = ''' 1. add contacts 2. delete contacts 3. search contacts 4. show all contacts 5. exit the system ''' #检测路径下是否存在通讯录文件,如果没有则建立文件 import os.path is_exist = os.path.isfile('addressbook.txt') if is_exist == 0: new_file = open('Contacts.txt', 'w') new_file.close() #入口程序 def start(): #设置循环,当用户输入特定选项退出 while True: print("Welcome, select a number:") print(txt) userchoice = int(input()) #输入错误序号则重启程序 if userchoice not in [1,2,3,4,5]: print('wrong choice') start() break #输入正确序号执行相应程序 elif userchoice == 1: add_contacts() elif userchoice == 2: delete_contacts() elif userchoice == 3: search_contacts() elif userchoice == 4: show_all_contacts() elif userchoice == 5: break #添加联系人 def add_contacts(): print('Add new contacts') print('Name: ', end = '') Name = input() print('Sex: ', end = '') Sex = input() print('Relationship(Friend/ Family/ Classmate): ', end = '') Relationship = input() print('Number: ', end = '') Number = input() #将通讯录追加到文件末端 Contacts_file = open('Contacts.txt','a') Contacts_file.write(Name+'\t'+Sex+'\t'+Relationship+'\t'+Number+'\n') Contacts_file.close() #删除通讯录中的信息 def delete_contacts(): print('Enter the name: ', end = '') name = input() Contacts_file = open('Contacts.txt', 'r') Contacts_list = [] #将通讯录缓存到列表内,遇到需要删除的通讯录条目则跳过 for line in Contacts_file.readlines(): if line.find(name) != -1: continue Contacts_list.append(line) #将通讯录清空,将缓存在列表中的通讯录信息加载进文件内 Contacts_file = open('Contacts.txt', 'w') for i in range(0, len(Contacts_list)): Contacts_file.write(Contacts_list[i]) Contacts_file.close() #搜索通讯录 def search_contacts(): print('Enter the name: ',end = '') Search_name = input() Contacts_file = open('addressbook.txt','r',encoding='utf-8') for line in Contacts_file.readlines(): String = line find_or_not = String.find(Search_name) if find_or_not !=-1 : print(line) break #若搜索不到,返回Not Found! if find_or_not == -1: print('Not Found!') Contacts_file.close() #显示通讯录所有条目 def show_all_contacts(): print('Name\tSex\tRelationship\tNumber', end = '\n') Contacts_file = open('addressbook.txt','r') print(Contacts_file.read()) Contacts_file.close() #执行入口程序 start()
效果还要我演示吗?你们自己运行试试行不!有问题留言哈!!