1.30云计算python作业

1.使用os和os.path以及函数的递归完成:
给出一个路径,遍历当前路径所有的文件及文件夹
打印输出所有的文件(遇到文件输出路径,遇到文件夹继续进文件夹)

import os
import os.path
def bianli(path):
    for item in os.listdir(path):
        full_path = os.path.join(path, item)
        if os.path.isfile(full_path):   # 判断是否是文件
            print(f"文件:{full_path}")

        elif os.path.isdir(full_path):  # 判断是否是文件夹
            bianli(full_path) # 递归遍历子文件夹
print(bianli("D:/test"))

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

import hashlib

# 定义存储账号密码的文件路径
DB_FILE = "D:/test/a/password.txt"

def encrypt_password(password):
    """
    对密码进行sha256加密
    """
    sha256 = hashlib.sha256()
    sha256.update(password.encode("utf-8"))     # 创建sha256对象,指定编码为utf-8
    return sha256.hexdigest()       # 返回加密后的字符串

def register():
    """用户注册功能"""
    username = input("请输入用户名:").strip()
    password = input("请输入密码:").strip()
    encrypted_pwd = encrypt_password(password)
    with open(DB_FILE, "a", encoding="utf-8") as f:
        f.write(f"{username}:{encrypted_pwd}\n")
    print("注册成功!")

def login():
    """用户登录功能"""
    username = input("请输入用户名:").strip()
    password = input("请输入密码:").strip()

    # 验证用户名和密码
    encrypted_pwd = encrypt_password(password)
    with open(DB_FILE, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            user, pwd = line.split(":", 1)
            if user == username and pwd == encrypted_pwd:
                print("登录成功!")
                return

    print("用户名或密码错误!")


def main():
    """主函数:提供注册/登录选择"""
    while True:
        print("\n===== 模拟登录系统 =====")
        print("1. 注册")
        print("2. 登录")
        print("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!")
main()

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

class Student:
    """学生类:封装学生属性和方法"""

    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  # 英语成绩
        self.total_score = self.calc_total()  # 总分(自动计算)

    def calc_total(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},{self.total_score}"

    @staticmethod
    def from_string(line):
        """从字符串解析为Student对象(用于读取文件)"""
        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)

class StudentManager:
    """学生信息管理类:封装录入、存储、读取、排序功能"""
    def __init__(self, file_path="D:/test/a/students.txt"):
        self.file_path = file_path  # 存储学生信息的文件路径

    def add_student(self):
        """录入单个学生信息"""
        stu_id = input("请输入学号(如2026001):").strip()
        name = input("请输入姓名:").strip()
        age = int(input("请输入年龄:").strip())
        chinese = float(input("请输入语文成绩:").strip())
        math = float(input("请输入数学成绩:").strip())
        english = float(input("请输入英语成绩:").strip())
        student = Student(stu_id, name, age, chinese, math, english)    #创建学生对象

        with open(self.file_path, "a", encoding="utf-8") as f:
            f.write(student.to_string() + "\n")                         #写入文件
        print(f"学生{name}(学号{stu_id})信息录入成功!")

    def read_students(self):
        """读取所有学生信息,返回Student对象列表"""
        students = []
        with open(self.file_path, "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)
        return students

    def sort_students_by_score(self):
        """按总分降序排序,总分相同按学号升序"""
        students = self.read_students()
        students.sort(key=lambda s: (-s.total_score, s.stu_id))
        # 打印排序结果
        print("\n===== 学生成绩排序结果(总分降序) =====")
        print(f"{'学号':<10}{'姓名':<8}{'年龄':<6}{'语文':<8}{'数学':<8}{'英语':<8}{'总分':<8}")
        print("-" * 60)
        for s in students:
            print(f"{s.stu_id:<10}{s.name:<8}{s.age:<6}{s.chinese:<8.1f}{s.math:<8.1f}{s.english:<8.1f}{s.total_score:<8.1f}")

def main():
    """主函数:提供功能菜单"""
    manager = StudentManager()
    while True:
        print("\n===== 学生信息管理系统 =====")
        print("1. 录入学生信息")
        print("2. 读取并按成绩排序")
        print("3. 退出")
        choice = input("请选择操作(1/2/3):").strip()

        if choice == "1":
            manager.add_student()
        elif choice == "2":
            manager.sort_students_by_score()
        elif choice == "3":
            print("已退出系统")
            break
        else:
            print("输入错误,请选择1/2/3!")
main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值