1 # -*- coding:utf-8 -*- 2 #输入用户名密码,正确登录,打印信息,可修改,存回文件 3 4 def print_user_info(account_dic,username): 5 person_info = account_dic[username] 6 msg = ''' 7 Name: %s 8 Age: %s 9 Job: %s 10 Dept: %s 11 Phone: %s 12 ''' % (person_info[2], 13 person_info[3], 14 person_info[4], 15 person_info[5], 16 person_info[6]) 17 print(msg) 18 19 def save_back_to_file(account_dic): 20 f.seek(0) 21 f.truncate() 22 for line in account_dic: 23 row = ','.join(account_dic[line]) 24 f.write('%s ' % row) 25 f.flush() 26 27 def update_user_info(account_dic,username): 28 person_info = account_dic[username] 29 print('old data:', person_info) 30 str = ['Username','Password','Name','Age','Job','Dept','Phone'] 31 for index, i in enumerate(person_info): 32 if index > 1: #用户名 密码 不显示 33 print('%s. %s: %s' % (index, str[index], i)) 34 choice = input('select column id to change >>>:').strip() 35 if choice.isdigit(): 36 choice = int(choice) 37 if choice > 1 and choice < len(person_info): 38 print('current value:', person_info[choice]) 39 new_val = input('new value:').strip() 40 if new_val: #不为空 41 person_info[choice] = new_val 42 print('new data:', person_info) 43 save_back_to_file(account_dic) 44 else: 45 print('不能为空!') 46 47 48 f = open('account.txt', 'r+', encoding='utf-8') 49 data = f.readlines() 50 # print(data) 51 account_dic = {} 52 53 for i in data: 54 items = i.replace(' ', '').split(',') 55 account_dic[items[0]] = items # 将文件读出来存到字典形式中 56 # print(account_dic) 57 58 msg = ''' 59 1.打印个人信息 60 2.修改个人信息 61 ''' 62 63 count = 0 64 while count < 3: 65 username = input('Username:').strip() 66 password = input('Password:').strip() 67 if username in account_dic: 68 if password == account_dic[username][1]: 69 print('welcome %s '.center(50,'-') % username) 70 while True: 71 print(msg) 72 user_choice = input('>>>:').strip() 73 if user_choice.isdigit(): 74 user_choice = int(user_choice) 75 if user_choice == 1: 76 print_user_info(account_dic,username) 77 elif user_choice == 2: 78 update_user_info(account_dic,username) 79 80 elif user_choice == 'q': 81 exit('bye bye') 82 else: 83 print('Wrong Username or password') 84 else: 85 print('Username dose not exist') 86 count += 1 87 else: 88 print('Too many attempts') 89 f.close()
附:account.txt
alice,123,静静,12,Model,IT,123456789
alex,123,李杰,40,CEO,IT,123456789
rain,123,王雨,27,Engineer,IT,123456789