作业1:使用os和os.path以及函数的递归完成:
给出一个路径,遍历当前路径所有的文件及文件夹
打印输出所有的文件(遇到文件输出路径,遇到文件夹继续进文件夹)
代码:
python
#导入os模块
import os
#定义遍历函数
def traverse_files(path):
#以列表形式返回目录下的所有文件及文件夹
files = os.listdir(path)
#路径拼接
for f in files:
real_path = os.path.join(path,f)
# 判断路径是文件还是文件夹
#是文件时,返回完整路径
if os.path.isfile(real_path):
print(os.path.abspath(real_path))
#是文件夹时,再次调用遍历函数
elif os.path.isdir(real_path):
traverse_files(real_path)
#其他情况
else:
print("其他情况")
pass
#调用函数
traverse_files("D:\云计算\python")
运行结果:




作业2:使用加密模块及IO模拟登录功能,要求使用文件模拟数据库存储用户名和密码
代码:
python
# 导入加密模块
import hashlib
#盐值
salt = "hahha!@@@@%$^"
# 密码加密函数
def encrypt_password(pwd):
md5_obj = hashlib.md5(pwd.encode("utf-8"))
md5_obj.update(salt.encode("utf-8"))
return md5_obj.hexdigest()
# 注册功能
def register():
print("\n===== 用户注册 =====")
username = input("请输入用户名:").strip()
password = input("请输入密码:").strip()
# 避免空用户名/密码
if not username or not password:
print("用户名和密码不能为空")
return
# 加密密码
encrypt_pwd = encrypt_password(password)
# 标记用户名是否已存在
is_exist = False
# 检查用户名唯一性(文件不存在则跳过,首次注册)
try:
with open("user_db.txt", "r", encoding="utf-8") as f:
for line in f:
line = line.strip() # 去除换行/空格
if line: # 跳过空行
exist_name, _ = line.split(":") # 拆分用户名和加密密码
if exist_name == username:
is_exist = True
break
except FileNotFoundError:
pass
if is_exist:
print("用户名已存在")
return
# 注册成功:追加写入文件
with open("user_db.txt", "a", encoding="utf-8") as f:
f.write(f"{username}:{encrypt_pwd}\n")
print("注册成功")
# 登录功能
def login():
print("\n===== 用户登录 =====")
username = input("请输入用户名:").strip()
password = input("请输入密码:").strip()
# 非空校验
if not username or not password:
print("用户名和密码不能为空")
return
# 加密输入的密码,用于和文件中存储的加密密码对比
input_encrypt_pwd = encrypt_password(password)
# 读取文件验证账号密码
try:
with open("user_db.txt", "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
exist_name, exist_encrypt_pwd = line.split(":")
# 先匹配用户名,再匹配加密密码
if exist_name == username:
if exist_encrypt_pwd == input_encrypt_pwd:
print("登录成功")
else:
print("密码输入错误")
return
# 遍历完文件未找到匹配用户名
print("用户名不存在")
except FileNotFoundError:
print("用户名不存在")
# 主菜单
if __name__ == "__main__":
while True:
print("\n===== 登录注册系统 =====")
print("1. 注册新用户 2. 用户登录 3. 退出系统")
choice = input("请选择操作(1/2/3):").strip()
if choice == "1":
register()
elif choice == "2":
login()
elif choice == "3":
print("退出系统")
break
else:
print("输入无效,请选择1/2/3")
运行结果:


作业3:使用面向对象编程完成学生信息录入功能,数据存储在本地文件txt中,并读取学生信息并按照成绩进行排序,学生其他属性自行规划
代码:
python
class StudentManager:
"""学生信息管理"""
def __init__(self):
# 初始化数据存储文件
self.file_path = "student.txt"
def add_student(self):
"""录入学生信息"""
print("\n===== 学生信息录入 =====")
sno = input("学号:").strip()
name = input("姓名:").strip()
total = input("总分:").strip()
# 1. 非空校验
if not (sno and name and total):
print("学号、姓名、总分不能为空")
return
# 2. 总分格式校验
try:
total = float(total)
except ValueError:
print("总分必须是数字(整数/小数)")
return
# 3. 学号唯一性校验
if self._is_sno_exist(sno):
print("学号已存在,不可重复")
return
# 追加写入文件
with open(self.file_path, "a", encoding="utf-8") as f:
f.write(f"{sno}:{name}:{total}\n")
print(f"录入成功!{name}({sno})总分:{total}")
def _is_sno_exist(self, sno):
"""私有方法"""
try:
with open(self.file_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip().split(":")[0] == sno:
return True
return False
except FileNotFoundError:
return False # 文件不存在则无重复学号
def sort_by_total(self):
"""读取所有学生信息,按总分降序排序并格式化打印"""
try:
with open(self.file_path, "r", encoding="utf-8") as f:
students = []
for line in f:
line = line.strip()
if line:
sno, name, total = line.split(":")
students.append({
"sno": sno,
"name": name,
"total": float(total)
})
except FileNotFoundError:
print("暂无学生信息,请先录入")
return
# 按总分降序排序
students_sorted = sorted(students, key=lambda x: x["total"], reverse=True)
# 格式化打印结果
print("\n===== 学生成绩排名(总分从高到低) =====")
print(f"{'排名':<4}{'学号':<6}{'姓名':<6}{'总分':<6}")
for i, s in enumerate(students_sorted, 1):
print(f"{i:<4}{s['sno']:<6}{s['name']:<6}{s['total']:<6.1f}")
# 主程序入口
if __name__ == "__main__":
manager = StudentManager()
while True:
print("\n===== 学生信息管理 =====")
print("1. 录入信息 2. 总分排序 3. 退出系统")
choice = input("请选择操作(1/2/3):").strip()
if choice == "1":
manager.add_student()
elif choice == "2":
manager.sort_by_total()
elif choice == "3":
print("退出系统")
break
else:
print("输入错误,请选择1/2/3")
运行结果:


