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!")
相关推荐
傻啦嘿哟1 小时前
Python列表排序:用key参数掌控排序规则
java·开发语言
Ronin3052 小时前
交换机路由管理模块
服务器·rabbitmq·动态规划·交换路由
大尚来也2 小时前
解决 IDEA 运行 Spring Boot 测试时“命令行过长”错误的终极方案
java·spring boot·intellij-idea
三点水-here2 小时前
03 - KV Cache与批处理:大模型推理的内存管理核心技术
服务器·人工智能·ai编程
0思必得02 小时前
[Web自动化] Selenium浏览器复用
前端·python·selenium·自动化
云姜.2 小时前
如何在idea上使用数据库
java·数据库·intellij-idea
yttandb2 小时前
linux的基础命令
linux·运维·服务器
未来之窗软件服务2 小时前
服务器运维(三十五)数字证书TLS 版本设备对照表—东方仙盟
运维·服务器·服务器运维·仙盟创梦ide·东方仙盟
-小麦子-2 小时前
Python 变量组包、解包及星号扩展机制详解
开发语言·python