作业 第三次

题目一

代码

python 复制代码
import os

def list_files(path):
    if os.path.isfile(path):
        print(path)
    elif os.path.isdir(path):
        for item in os.listdir(path):
            list_files(os.path.join(path, item))

运行结果

题目二

代码

python 复制代码
import hashlib
import os

USER_DB = 'users.txt'

def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

def register(username, password):
    with open(USER_DB, 'a') as f:
        f.write(f"{username}:{hash_password(password)}\n")
    print("注册成功")

def login(username, password):
    if not os.path.exists(USER_DB):
        return False
    with open(USER_DB, 'r') as f:
        for line in f:
            u, p = line.strip().split(':')
            if u == username and p == hash_password(password):
                return True
    return False

运行结果

题目三

代码

python 复制代码
class Student:
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score
    
    def __repr__(self):
        return f"{self.name},{self.age},{self.score}"

class StudentSystem:
    FILE_NAME = 'students.txt'
    
    def add_student(self, student):
        with open(self.FILE_NAME, 'a', encoding='utf-8') as f:
            f.write(str(student) + '\n')
    
    def read_and_sort(self):
        students = []
        with open(self.FILE_NAME, 'r', encoding='utf-8') as f:
            for line in f:
                name, age, score = line.strip().split(',')
                students.append(Student(name, int(age), int(score)))
        
        students.sort(key=lambda s: s.score, reverse=True)
        return students

运行结果

相关推荐
南 阳4 分钟前
Python从入门到精通day58
开发语言·python
楚Y6同学4 分钟前
为什么 C++ 要设计函数重载
开发语言·c++
steins_甲乙4 分钟前
【无标题】
开发语言·c++
码云数智-大飞5 分钟前
PHP OPcache 深度调优:从性能陷阱到生产环境最佳实践
开发语言
weixin_433179335 分钟前
Python - 调试
java·开发语言·python
代码探秘者6 分钟前
【算法篇】6.分治
java·数据结构·后端·python·算法·排序算法
Elastic 中国社区官方博客6 分钟前
我们如何修复 OpenTelemetry 中基于 head 的采样
大数据·开发语言·python·elasticsearch·搜索引擎
20岁30年经验的码农8 分钟前
Java NIO底层实现原理
开发语言·php
飞鱼计划12 分钟前
EasyExcel 3.3.2 模板方式写入数据完整指南
java·开发语言
梦因you而美13 分钟前
Python自动化复制Excel sheet表(openpyxl+win32com双方案,完美保留格式)
python·自动化·excel·win32com·openpyxl