1. 项目概述Python实现文本账号密码读取与登录验证这个练习项目非常适合刚接触Python文件操作和基础逻辑的新手。核心目标是从文本文件中读取预先存储的用户名和密码然后通过控制台输入进行登录验证。这种场景在实际开发中非常常见比如批量测试账号、自动化脚本登录等场景。我见过不少初学者在这个练习中踩坑主要集中在文本编码处理、密码输入隐藏和验证逻辑设计三个环节。下面我会结合十年Python开发经验带你完整实现这个功能并分享几个教科书上不会写的实战技巧。2. 核心实现步骤详解2.1 准备账号密码文本文件首先创建accounts.txt文本文件建议使用UTF-8编码避免中文乱码问题。账号密码的存储格式有多种选择# 格式1每行一对账号密码用空格分隔 admin 123456 user1 password123 # 格式2使用JSON格式更规范 [ {username: admin, password: 123456}, {username: user1, password: password123} ]实际项目中强烈推荐使用格式2因为支持特殊字符如包含空格的密码可扩展附加字段如用户角色、有效期等有现成的Python json模块支持2.2 文件读取与解析基础文本处理方案def load_accounts(file_path): accounts {} try: with open(file_path, r, encodingutf-8) as f: for line in f: line line.strip() # 去除首尾空白字符 if line and not line.startswith(#): # 跳过空行和注释 username, password line.split(maxsplit1) accounts[username] password except FileNotFoundError: print(f错误文件 {file_path} 不存在) except Exception as e: print(f文件读取错误: {str(e)}) return accountsJSON格式处理方案推荐import json def load_accounts_json(file_path): try: with open(file_path, r, encodingutf-8) as f: return {acc[username]: acc[password] for acc in json.load(f)} except json.JSONDecodeError: print(错误JSON格式解析失败) except Exception as e: print(f文件读取错误: {str(e)}) return {}2.3 登录验证实现import getpass # 安全输入密码的模块 def login(accounts): username input(用户名: ).strip() # 安全输入密码不会回显 password getpass.getpass(密码: ) if username in accounts and accounts[username] password: print(登录成功) return True else: print(用户名或密码错误) return False关键点说明使用getpass模块可以避免密码输入时显示明文strip()处理用户输入的首尾空格先检查用户名存在性再验证密码避免密钥时序攻击3. 完整代码实现与优化3.1 基础版本完整代码import getpass def main(): # 加载账号数据 accounts load_accounts(accounts.txt) if not accounts: print(账号库为空请检查文件内容) return # 登录尝试最多3次 for attempt in range(3): if login(accounts): break print(f剩余尝试次数: {2 - attempt}) else: print(登录失败次数过多程序退出) if __name__ __main__: main()3.2 安全增强版import hashlib def secure_login(accounts): username input(用户名: ).strip() if username not in accounts: # 统一提示用户名或密码错误避免暴露账号存在性 print(用户名或密码错误) return False # 密码加盐哈希验证 input_pass getpass.getpass(密码: ) stored_pass accounts[username] salt stored_pass[:32] # 假设存储的是salt:hash格式 input_hash hashlib.pbkdf2_hmac( sha256, input_pass.encode(), salt.encode(), 100000 ).hex() if input_hash stored_pass[33:]: print(登录成功) return True else: print(用户名或密码错误) return False4. 常见问题与解决方案4.1 编码问题排查当遇到以下错误时UnicodeDecodeError: gbk codec cant decode byte...解决方案明确指定文件编码with open(filepath, r, encodingutf-8) as f:使用编码自动检测安装chardet包import chardet def detect_encoding(filepath): with open(filepath, rb) as f: return chardet.detect(f.read())[encoding]4.2 路径问题处理相对路径可能因执行目录不同而失效建议import os # 获取脚本所在目录 base_dir os.path.dirname(os.path.abspath(__file__)) file_path os.path.join(base_dir, accounts.txt)4.3 性能优化建议当账号数量较大时10万条改用SQLite数据库使用shelve模块持久化字典实现分页加载机制5. 项目扩展方向5.1 添加密码强度检查import re def check_password_strength(password): if len(password) 8: return False if not re.search(r[A-Z], password): return False if not re.search(r[a-z], password): return False if not re.search(r[0-9], password): return False return True5.2 实现密码修改功能def change_password(accounts, filepath): username input(请输入用户名: ) if username not in accounts: print(用户不存在) return old_pass getpass.getpass(原密码: ) if accounts[username] ! old_pass: print(原密码错误) return new_pass getpass.getpass(新密码: ) if not check_password_strength(new_pass): print(密码强度不足) return accounts[username] new_pass save_accounts(accounts, filepath) print(密码修改成功)5.3 日志记录功能import logging from datetime import datetime logging.basicConfig( filenameauth.log, levellogging.INFO, format%(asctime)s - %(message)s ) def log_login_attempt(username, success): status 成功 if success else 失败 logging.info(f登录尝试 - 用户名: {username}, 状态: {status})这个项目虽然基础但涵盖了文件I/O、数据结构、输入验证等多个Python核心知识点。建议在实现基础功能后尝试添加更多安全特性如密码加密、登录次数限制等这对理解实际开发中的安全规范很有帮助。