Python银行程序开发:实现文件同行列的用户名密码逐行验证
问题
我正在开发一款Python银行程序,目前遇到的问题是:无法实现逐行读取ANZData.txt文件,验证用户输入的用户名和密码是否同时存在于文件的同一行中。我曾尝试编写代码if loginuser and loginpass in file.readlines(),但运行报错,不知如何解决。现有代码如下:
accounts = {} def login(): f = open("ANZData.txt", "a") y = 0 count = 0 while y != 1: print("whats your username? ") loginuser = input() print("whats your password? ") loginpass = input() print("whats your PIN ") loginpass = input() # Open the file in read mode with open('ANZData.txt', 'r') as file: # Read each line in the file for line in file: #CODE NEEDED HERE def register(accounts): print("what is your username?") user = input("enter username:") print("what is your Password? ") passw = input("enter password: ") print("please provide us a pin number to use") PIN = input("enter PIN: ") with open('ANZData.txt', 'a') as f: f.write("name: " + user + " Password: " + passw + " PIN: " + PIN + '\n') with open('ANZData.txt', 'r') as file: for line in file: key, value = line.strip().split(':', 1) accounts[key.strip()] = value.strip() print(accounts) #Main code starts here: #--------------------------------------------------------------------------------------------# x=1 while x != 0: print(accounts) print("Would you like to login or register?") logintoken = input("") if logintoken == "enter": registr = register(accounts) elif logintoken == "login": x=0 logi = login() else: print("try again") x=1 while x != 0: print(accounts) print("\n Do you want to withdraw, deposit or check balance?") decision = input("") if decision.upper == "Balance": print("placeholder")
解决方案
先梳理代码里的核心问题:
- 变量覆盖:login函数中,用户输入的密码被后续输入的PIN覆盖(都用了
loginpass变量),导致密码验证根本无法进行 - 逻辑错误:
if loginuser and loginpass in file.readlines()的语法逻辑不对,这个表达式实际是判断loginuser为真且loginpass在所有行的列表里,不是验证两者在同一行 - 资源泄漏:login函数开头
f = open("ANZData.txt", "a")打开文件后未关闭,应该用with语句自动管理文件资源
修复后的login函数代码:
def login(): while True: print("whats your username? ") login_user = input().strip() print("whats your password? ") login_pass = input().strip() print("whats your PIN? ") login_pin = input().strip() # 逐行验证用户输入 authenticated = False with open('ANZData.txt', 'r') as file: for line in file: line = line.strip() if not line: continue # 跳过空行 # 按格式拆分每行内容:"name: xxx Password: yyy PIN: zzz" parts = line.split() # 提取对应字段 stored_user = parts[1] stored_pass = parts[3] stored_pin = parts[5] # 验证输入与存储内容是否匹配 if stored_user == login_user and stored_pass == login_pass and stored_pin == login_pin: authenticated = True break if authenticated: print("登录成功!") break else: print("用户名、密码或PIN错误,请重新输入!")
额外优化建议:
- register函数的字典构建问题:当前用
split(':', 1)拆分行会导致账户信息存储错误,可修改为:
with open('ANZData.txt', 'r') as file: accounts.clear() for line in file: line = line.strip() if not line: continue parts = line.split() user = parts[1] accounts[user] = { 'password': parts[3], 'pin': parts[5] }
- 主逻辑的语法错误:
if decision.upper == "Balance"需改为if decision.upper() == "BALANCE",因为upper是字符串方法,必须调用才会返回大写结果
内容的提问来源于stack exchange,提问作者Atem Arok
相关产品推荐
相关产品推荐

