写两道python进阶题
第一题
"""
使用os和os.path以及函数的递归完成:
给出一个路径,遍历当前路径所有的文件及文件夹
打印输出所有的文件(遇到文件输出路径,遇到文
件夹继续进文件夹)
"""
import os
def print_all_files(dir_path):
"""
递归遍历目录,打印所有文件的完整路径
:param dir_path: 要遍历的目录路径
"""
# 先判断路径是否合法存在
if not os.path.exists(dir_path):
print(f"错误:路径 {dir_path} 不存在")
return
if not os.path.isdir(dir_path):
print(f"错误:{dir_path} 不是一个有效目录")
return
# 遍历当前目录下的所有条目(文件+文件夹)
for item_name in os.listdir(dir_path):
# 拼接成完整路径(必须用os.path.join,兼容不同操作系统)
full_path = os.path.join(dir_path, item_name)
# 判断:如果是文件,直接打印路径
if os.path.isfile(full_path):
print(full_path)
# 判断:如果是目录,递归调用自身,进入子目录继续遍历
elif os.path.isdir(full_path):
print_all_files(full_path)
if __name__ == '__main__':
target = input("请输入要遍历的目录路径:")
print_all_files(target)

———————————————————————————————————————————
第二题
"""
2.使用加密模块及I0模拟登录功能,要求使用文件
模拟数据库存储用户名和密码。
"""
import hashlib
# 密码加密
def enc(pwd):
return hashlib.md5(pwd.encode()).hexdigest()
# 注册:写入文件
def register(user, pwd):
with open("user.txt", "a") as f:
f.write(f"{user}:{enc(pwd)}\n")
# 登录:读取校验
def login(user, pwd):
pwd_md5 = enc(pwd)
with open("user.txt", "r") as f:
for line in f:
u, p = line.strip().split(":")
if u == user and p == pwd_md5:
print("登录成功")
return
print("登录失败")
register("test", "123456")
login("test", "123456")
login("test1", "123456")

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构
更多推荐


所有评论(0)