基础-python日常练习-习题③
任务1.import osdef traverse_dir(path):# 遍历路径下所有内容for item in os.listdir(path):full_path os.path.join(path, item)# 判断是否文件夹递归进入if os.path.isdir(full_path):traverse_dir(full_path)# 是文件直接打印完整路径elif os.path.isfile(full_path):print(full_path)if __name__ __main__:target_path input(请输入要遍历的文件夹路径)if os.path.exists(target_path):traverse_dir(target_path)else:print(路径不存在)任务2.import hashlibimport os# 密码md5加密函数def encrypt_pwd(raw_pwd):md5_obj hashlib.md5(raw_pwd.encode(utf-8))return md5_obj.hexdigest()# 注册用户写入文件 格式 用户名:加密密码def register(username, password, db_fileuser.db):encrypt encrypt_pwd(password)# 检查用户是否已存在if check_user_exist(username, db_file):print(用户名已注册)return Falsewith open(db_file, a, encodingutf-8) as f:f.write(f{username}:{encrypt}\n)print(注册成功)return True# 检查用户是否存在def check_user_exist(username, db_fileuser.db):if not os.path.exists(db_file):return Falsewith open(db_file, r, encodingutf-8) as f:for line in f:line line.strip()if not line:continueuname, _ line.split(:)if uname username:return Truereturn False# 登录校验def login(username, password, db_fileuser.db):if not os.path.exists(db_file):print(暂无用户数据请先注册)return Falseinput_encrypt encrypt_pwd(password)with open(db_file, r, encodingutf-8) as f:for line in f:line line.strip()if not line:continueuname, pwd_enc line.split(:)if uname username and pwd_enc input_encrypt:print(登录成功欢迎用户, username)return Trueprint(用户名或密码错误)return False# 交互菜单def main():while True:print(\n 用户系统 )print(1. 注册账号)print(2. 用户登录)print(3. 退出程序)opt input(请选择操作)if opt 1:un input(输入用户名)pw input(输入密码)register(un, pw)elif opt 2:un input(输入用户名)pw input(输入密码)login(un, pw)elif opt 3:print(程序退出)breakelse:print(输入错误请重新选择)if __name__ __main__:main()