Python处理文本文件键值对的两类技术问题求助
解决Python文本文件键值对处理的两个问题
问题一:登录匹配成功后终止循环
当前登录代码会遍历文件所有行,即便找到匹配的用户仍会继续循环,且每一行不匹配时都会打印错误信息,逻辑不合理。以下是修正方案:
修正思路
- 找到匹配的用户名和密码后,执行对应角色函数,立即终止循环并返回,避免无效遍历。
- 不在循环内逐行打印错误,仅当遍历完所有行都未找到匹配项时,再统一提示用户名或密码错误。
修正后的代码
import ast def login(userinput, passinput): login_db = "login.txt" found_user = False with open(login_db, 'r') as f: for single_line in f: try: dict_to_check = ast.literal_eval(single_line) username = dict_to_check['Username'] password = dict_to_check['Password'] role = dict_to_check['Role'] if userinput == username: found_user = True if passinput == password: if role == 'Immigration officer': Immigration() elif role == 'Customs officer': Customs() else: print('Incorrect role you do not have the authority.') # 匹配成功,终止循环 return else: print('Password is incorrect.') # 用户名匹配但密码错误,无需继续遍历 return except Exception as e: print(f"An exception occurred: {e}") # 遍历完所有行未找到匹配用户名 if not found_user: print('Incorrect username')
问题二:修改乘客文件中的Status值
文本文件无法直接修改单行内容,需先将所有数据读取到内存,修改对应项后再重新写入文件。
修正思路
- 读取文件所有行,转换为字典列表存储。
- 找到目标Civil ID对应的字典,修改其Status值。
- 将修改后的字典列表重新写入原文件。
修正后的代码
import ast def Existing_passenger(ID): passenger_db = "passenger.txt" # 读取所有乘客数据到内存 passengers = [] with open(passenger_db, 'r') as f: for single_line in f: try: passenger_dict = ast.literal_eval(single_line) passengers.append(passenger_dict) except Exception as e: print(f"An exception occurred when reading data: {e}") # 查找并修改目标乘客的Status updated = False for idx, p in enumerate(passengers): try: if p['Civil ID'] == ID: print("-Passenger's information-") print(f'Name: {p["Name"]}\nDate of birth: {p["DOB"]}\nGender: {p["Gender"]}\nCustoms fine: {p["Customs fine"]}\nStatus: {p["Status"]}\n') print('A. Arrival Approved\nB. Arrival Rejected\nC. Departure Approved\nD. Departure Rejected\nE. Go Back to previous menu') status_input = input('Select one of the following options: ') if status_input == 'A': if p['Status'] == '': p['Status'] = 'Arrival Approved' updated = True elif status_input == 'B': p['Status'] = 'Arrival Rejected' updated = True elif status_input == 'C': p['Status'] = 'Departure Approved' updated = True elif status_input == 'D': p['Status'] = 'Departure Rejected' updated = True elif status_input == 'E': print('Returning to previous menu...') return else: print('Wrong entry, please try again.') Existing_passenger(ID) return break except Exception as e: print(f"An exception occurred: {e}") # 将修改后的数据写回文件 if updated: with open(passenger_db, 'w') as f: for passenger in passengers: f.write(f"{passenger}\n") print('Passenger status updated successfully.') else: print('No passenger found with the given Civil ID.')
额外提示
- 用
ast.literal_eval解析字典字符串可行,但如果文件格式标准化,更推荐使用JSON格式(将单引号改为双引号),通过json模块读写,安全性和兼容性更强。 - 避免使用空
except捕获所有异常,建议捕获具体异常类型(如SyntaxError、KeyError),便于排查问题。
内容的提问来源于stack exchange,提问作者Kilmton Starvy
相关产品推荐
相关产品推荐

