如何将文本文件中的账号密码导入Python字典用于登录验证
实现文本文件转登录验证用Python字典
假设文本文件格式
假设你的凭证文件名为credentials.txt,内容格式为每行一个用户名,密码对:
username,password
user2,password2
user3,password3
基础实现代码
通过逐行读取文件内容,分割字段后构建字典:
Database = {} # 自动管理文件资源,避免泄漏 with open('credentials.txt', 'r') as file: for line in file: # 去除换行符等空白字符,按逗号分割字段 cleaned_line = line.strip() if not cleaned_line: # 跳过空行 continue parts = cleaned_line.split(',') if len(parts) == 2: # 确保每行格式符合要求 username, password = parts Database[username] = password # 输出验证结果 print(Database)
简洁版实现(字典推导式)
用一行代码完成字典构建,同时过滤无效行:
with open('credentials.txt', 'r') as file: Database = { parts[0]: parts[1] for line in file if (parts := line.strip().split(',')) and len(parts) == 2 } print(Database)
登录验证示例
生成的Database可直接用于校验账号密码:
def check_login(input_user, input_pwd): return input_user in Database and Database[input_user] == input_pwd # 测试用例 print(check_login('user3', 'password3')) # 输出 True print(check_login('user1', 'wrong_pwd')) # 输出 False
内容的提问来源于stack exchange,提问作者Slayer21
相关产品推荐
相关产品推荐

