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!")
相关推荐
AAI机器之心几秒前
这个RAG框架绝了:无论多少跳,LLM只调用两次,成本暴降
人工智能·python·ai·llm·agent·产品经理·rag
Fairy要carry2 分钟前
项目01-手搓Agent之loop
前端·javascript·python
齐齐大魔王15 分钟前
linux-核心工具
linux·运维·服务器
醇氧15 分钟前
Linux 系统的启动过程
linux·运维·服务器
皙然15 分钟前
深入拆解MESI协议:从原理到实战,搞懂CPU缓存一致性的核心机制
java·缓存
IMPYLH16 分钟前
Linux 的 dircolors 命令
linux·运维·服务器·数据库
郝学胜-神的一滴16 分钟前
【技术实战】500G单行大文件读取难题破解!生成器+自定义函数最优方案解析
开发语言·python·程序人生·面试
齐齐大魔王19 分钟前
linux-基础操作
linux·运维·服务器
愤豆20 分钟前
02-Java语言核心-语法特性-注解体系详解
java·开发语言·python
一个有温度的技术博主25 分钟前
网安实验系列二:服务器信息收集
运维·服务器