python作业3

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

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

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

python 复制代码
​
import  os
from os import  path
import  sys
def file(url):
    files = os.listdir(url)
    for f in files:
        real_path=path.join(url,f)
        if path.isfile(real_path):
            print(path.abspath(real_path))
        elif path.isdir(real_path):
            file(real_path)
        else:
            print("特殊情况")
            pass
ls="d:\云1"
file(ls)

​

结果:

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

python 复制代码
import hashlib
import hmac

def encryption_admin(str):
    salt="*****!!!!".encode("utf-8")
    return hmac.new(salt,str.encode("utf-8"),"md5").hexdigest()
def load_user_from_ku():
    user_data = {}
    file_path = r"d:\云1\6python-oop\ku"
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read().strip()
        stored_username, stored_pwd = content.split(" ")
        user_data["username"] = encryption_admin(stored_username)
        user_data["password"] = encryption_admin(stored_pwd)
    return user_data
database = load_user_from_ku()
username,password=input("请输入用户名和密码并使用空格分隔:").split(" ")
if(encryption_admin(username)==database["username"] 
   and encryption_admin(password)==database["password"]):
    print("login")
else:
    print("error")

运行结果:

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

python 复制代码
class Student:
    def __init__(self, name, number, chinese, math, english):
        self.name = name
        self.number = number
        self.chinese = chinese
        self.math = math
        self.english = english
        self.total = chinese + math + english
 
    def to_string(self):
        return f"{self.name}|{self.number}|{self.chinese}|{self.math}|{self.english}|{self.total}"
 
    def from_string(self, line):
        parts = line.strip().split("|")
        self.name = parts[0]
        self.number = parts[1]
        self.chinese = int(parts[2])
        self.math = int(parts[3])
        self.english = int(parts[4])
        self.total = self.chinese + self.math + self.english
        return self
 
 
class StudentManager:
    def __init__(self, file_path="stu.txt"):
        self.file_path = file_path
 
    def add_student(self, student):
        with open(self.file_path, "a", encoding="utf-8") as f:
            f.write(student.to_string() + "\n")
        print(f"学生 {student.name} 信息已保存到文件!")
 
    def load_students(self):
        students = []
        with open(self.file_path, "r", encoding="utf-8") as f:
            for line in f:
                if line.strip():
                    student = Student("", "", 0, 0, 0)
                    student.from_string(line)
                    students.append(student)
        return students
 
    def sort_students(self, students, key_field="math", reverse=False):
        valid_fields = ["chinese", "math", "english", "total"]
        students.sort(key=lambda s: getattr(s, key_field), reverse=reverse)
        return students
 
 
manager = StudentManager()
 
while True:
    running = int(input("请选择要进行的操作:1.继续录入  2.退出\n"))
    if running == 1:
        name = input("请输入学生姓名:")
        number = input("请输入学生的学号:")
        chinese = int(input("请输入学生的语文成绩:"))
        math = int(input("请输入学生的数学成绩:"))
        english = int(input("请输入学生的英语成绩:"))
        student = Student(name, number, chinese, math, english)
        manager.add_student(student)
    else:
        break
 
students = manager.load_students()
print("\n排序前:")
for s in students:
    print(s.to_string())
 
sorted_students = manager.sort_students(students, key_field="math")
print("\n按数学成绩排序后:")
for s in sorted_students:
    print(s.to_string())

运行结果:

相关推荐
xywww16821 分钟前
大模型 API 选型实战:GPT、Gemini、Claude 接入时该看哪些指标?
运维·服务器·人工智能·python·gpt·langchain
夜雪一千5 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
能有时光6 小时前
PyTorch KernelAgent 源码解读 ---(4)--- ExtractorAgent
人工智能·pytorch·python
_Jimmy_6 小时前
Python 协程库如何使用以及有哪些使用场景
python
aqi007 小时前
15天学会AI应用开发(十七)使用LangGraph实现会话记忆功能
人工智能·python·大模型·ai编程·ai应用
西门吹-禅7 小时前
java springboot N+1问题
java·开发语言·spring boot
第一程序员7 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
skywalk81637 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
weixin_BYSJ19877 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
IT笔记9 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust