Python 第三次作业

1.使用os和os.path以及函数的递归完成:

给出一个路径,遍历当前路径所有的文件及文件夹

打印输出所有的文件(遇到文件输出路径,遇到文件夹继续进文件夹)

python 复制代码
import os
def traversal_file (path):
    if not os.path.exists(path):
        print(f"{path}路径不存在")
        return
    if not os.path.isdir(path):
        print(f"{path}不是有效的文件夹路径")
        return
    try:
        for file_name in os.listdir(path):
            full_path = os.path.join(path,file_name)
            if os.path.isfile(full_path):
                print(f"{full_path}文件")
            elif os.path.isdir(full_path):
                traversal_file(full_path)
    except PermissionError:
        print(f"无法访问该路径{path}")
if __name__ == "__main__" :
    target_path = input("请输入要遍历的路径:").strip()
    traversal_file(target_path)

2.使用加密模块及IO模拟登录功能,要求使用文件模拟数据库存储用户名和密码。

python 复制代码
import hashlib
MARIADB_FILE = "mariadb.txt"
def encryption_passwd(password):
    salt = "python_secure_2026"
    password_with_salt = (password + salt).encode("utf-8")
    md5_obj = hashlib.md5(password_with_salt)
    return md5_obj.hexdigest()

def register(username,password):
    if user_exists(username):
        print(f"用户{username}已存在")
        return False
    encryption_pwd =encryption_passwd(password)
    try:
        with open(MARIADB_FILE,"a",encoding="utf-8") as f :
            f.write(f"{username}:{encryption_pwd}\n")
        print(f"用户{username}注册成功")
        return True
    except Exception as e :
        print(f"注册失败")
        return False

def user_exists(username):
    try:
        with open(MARIADB_FILE,"r",encoding="utf-8") as f :
            for line in f :
                line = line.strip()
                if not line:
                    continue
                user, _ = line.split(":", 1)
                if user == username:
                    return True
        return False
    except FileNotFoundError:
        return False
    
def login(username,password):
    encryption_input_pwd = encryption_passwd(password)
    try:
        with open(MARIADB_FILE,"r",encoding="utf-8") as f:
            for line in f :
                line = line.strip()
                if not line:
                    continue
                user, stored_pwd = line.split(":",1)
                if user == username:
                    if stored_pwd == encryption_input_pwd:
                        print(f"用户{username}登陆成功")
                        return True
                    else:
                        print("登陆失败,密码错误")
                        return False
        print(f"用户{username}不存在")
        return False
    except FileNotFoundError:
        print("用户数据库文件不存在,请先注册")

if __name__ == "__main__":
    while True:
        print("\n1.注册新用户")
        print("2.用户登录")
        print("3.退出系统")
        choice = input("请选择操作").strip()
        if choice == "1":
            username = input("请输入用户名:").strip()
            password = input("请输入密码:").strip()
            if not username or not password:
                print ("不能为空")
                continue
            register(username,password)
        elif choice == "2":
            username = input("请输入用户名:").strip()
            password = input("请输入密码:").strip()
            if not username or not password:
                print ("不能为空")
                continue
            login(username,password)
        elif choice == "3":
            print("退出系统")
            break
        else:
            print("输入错误,请选择1,2,3")

3.使用面向对象编程完成学生信息录入功能,数据存储在本地文件txt中,并读取学生信息并按照成绩进行排序,学生其他属性自行规划

python 复制代码
class Student:
    DATA_FILE = "students.txt"

    def __init__(self,stu_id,name,age,chinese,math,english):
        self.stu_id = stu_id
        self.name = name
        self.age = age
        self.chinese = chinese
        self.math = math
        self.english = english
    @property
    def total_score(self):
        return self.chinese + self.math + self.english
    def to_string(self):
        return f"{self.stu_id},{self.name},{self.age},{self.chinese},{self.math},{self.english}"
    
    @staticmethod
    def from_string(line):
        parts = line.strip().split(",")
        stu_id = parts[0]
        name = parts[1]
        age = int(parts[2])
        chinese = float(parts[3])
        math = float(parts[4])
        english = float(parts[5])
        return Student(stu_id,name,age,chinese,math,english)
    def __str__(self):
        return (f"学号:{self.stu_id} | 姓名:{self.name} | 年龄:{self.age} "
                f"| 语文:{self.chinese} | 数学:{self.math} | 英语:{self.english} "
                f"| 总分:{self.total_score}")

def add_student():
    while True:
        stu_id = input("请输入学号(如2026001,唯一):").strip()
        if not stu_id:
            print("学号不能为空!")
            continue
        if check_stu_id_exists(stu_id):
            print(f"学号 {stu_id} 已存在")
            continue
        break

    name = input("请输入姓名:").strip()
    while True:
        try:
            age = int(input("请输入年龄:").strip())
            if age <= 0 or age > 100:
                print("年龄需在1-100之间")
                continue
            break
        except ValueError:
            print("年龄必须是数字")

    def input_score(subject):
        while True:
            try:
                score = float(input(f"请输入{subject}成绩(0-100):").strip())
                if score < 0 or score > 100:
                    print(f"{subject}成绩需在0-100之间")
                    continue
                return score
            except ValueError:
                print(f"{subject}成绩必须是数字")

    chinese = input_score("语文")
    math = input_score("数学")
    english = input_score("英语")

    student = Student(stu_id, name, age, chinese, math, english)

    try:
        with open(Student.DATA_FILE, "a", encoding="utf-8") as f:
            f.write(student.to_string() + "\n")
        print(f"学生 {name} 信息录入成功!")
    except Exception as e:
        print(f"录入失败:{e}")

def check_stu_id_exists(stu_id):
    try:
        with open(Student.DATA_FILE, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                s_id = line.split(",")[0]
                if s_id == stu_id:
                    return True
        return False
    except FileNotFoundError:
        return False
    except Exception as e:
        print(f"校验学号出错:{e}")
        return False

def read_and_sort_students():
    students = [] 

    try:
        with open(Student.DATA_FILE, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                student = Student.from_string(line)
                students.append(student)

        if not students:
            print("暂无学生信息,请先录入!")
            return
        students_sorted = sorted(students, key=lambda s: s.total_score, reverse=True)

        for idx, s in enumerate(students_sorted, 1):
            print(f"第{idx}名:{s}")

    except FileNotFoundError:
        print("学生信息文件不存在,请先录入!")
    except Exception as e:
        print(f"读取/排序失败:{e}")

if __name__ == "__main__":
    while True:
        print("\n1. 录入学生信息")
        print("2. 查看并排序学生信息")
        print("3. 退出系统")
        choice = input("请选择操作(1/2/3):").strip()

        if choice == "1":
            add_student()
        elif choice == "2":
            read_and_sort_students()
        elif choice == "3":
            print("退出系统")
            break
        else:
            print("输入错误,请选择1/2/3!")
相关推荐
方便面不加香菜7 小时前
Linux--基础IO(一)
linux·运维·服务器
xieliyu.9 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
love530love9 小时前
LiveTalking 数字人项目 Windows 部署完全指南(EPGF 架构)
人工智能·windows·python·架构·livetalking·epgf
遇事不決洛必達9 小时前
【Python基础】GIL 锁是什么及其对爬虫的影响
爬虫·python·线程·进程·gil锁
明夜之约9 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee9 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Jinkxs9 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
辣机小司9 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
CryptoPP10 小时前
快速对接东京证券交易所API数据:实战指南与代码示例
开发语言·人工智能·windows·python·信息可视化·区块链
fangdengfu12310 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch