1,使用os和os.path以及函数的递归完成:
给出一个路径,遍历当前路径所有的文件及文件夹
打印输出所有的文件(遇到文件输出路径,遇到文件夹继续进文件夹)
import os
def list_all_files(path: str):
for entry in os.listdir(path):
full = os.path.join(path, entry)
if os.path.isfile(full):
print(full)
else:
list_all_files(full)
if __name__ == '__main__':
root = input('请输入要遍历的目录:').strip()
if os.path.isdir(root):
list_all_files(root)
else:
print('路径无效!')
运行截图

使用加密模块及IO模拟登录功能,要求使用文件模拟数据库存储用户名和密码。
# 模拟数据库文件名
DB = 'users.txt'
def register():
"""注册:追加写入 用户名:密码"""
name = input('用户名:').strip()
if not name or ':' in name:
print('名字非法!')
return
# 简单查重
with open(DB, 'a+', encoding='utf-8') as f:
f.seek(0)
for line in f:
if line.split(':')[0] == name:
print('用户已存在!')
return
pwd = input('密码:').strip()
if not pwd:
print('密码不能为空!')
return
f.write(f'{name}:{pwd}\n')
print('注册成功!')
def login():
"""登录:逐行比对"""
name = input('用户名:').strip()
pwd = input('密码:').strip()
with open(DB, encoding='utf-8') as f:
for line in f:
u, p = line.strip().split(':')
if u == name and p == pwd:
print('登录成功!')
return
print('用户名或密码错误!')
# 主菜单
if __name__ == '__main__':
while True:
choice = input('1注册 2登录 其他退出> ').strip()
if choice == '1':
register()
elif choice == '2':
login()
else:
break
运行截图


1265

被折叠的 条评论
为什么被折叠?



