第三次python作业

第一题

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

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

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

代码

python 复制代码
import os


def test1(path):
    """递归遍历路径,打印所有文件和文件夹"""
    items = os.listdir(path)

    for item in items:
        full_path = os.path.join(path, item)

        if os.path.isfile(full_path):
            print(f"文件: {full_path}")

        elif os.path.isdir(full_path):
            print(f"文件夹: {full_path}")
            test1(full_path)  # 递归进入子文件夹

    print()  # 每个目录遍历完后空一行

print("请输入要遍历的路径:")
path = input("路径: ")
test1(path)

运行

第二题

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

代码

python 复制代码
import hashlib

def hash_pwd(pwd):
    return hashlib.sha256(pwd.encode()).hexdigest()

def register(name, pwd):
    open("users.txt", "a").write(f"{name},{hash_pwd(pwd)}\n")

def login(name, pwd):
    for line in open("users.txt"):
        n, p = line.strip().split(",")
        if n == name and p == hash_pwd(pwd):
            return True
    return False

while True:
    c = input("1注册 2登录 3退出:")
    if c == "1":
        register(input("用户名:"), input("密码:"))
    elif c == "2":
        print("成功" if login(input("用户名:"), input("密码:")) else "失败")
    else:
        break

运行

第三题

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

代码

python 复制代码
class Student(object):
    def __init__(self, name, age,score):
        self.name = name
        self.age = age
        self.score =score

class StudentManager:
    def __init__(self):
        self.students = []
        self.load()

    def add(self,name,age,score):
        self.students.append(Student(name,age,score))
        self.save()

    def save(self):
        with open("students.txt","w") as f:
            for s in self.students:
                f.write(f"{s.name},{s.age},{s.score}\n")

    def show(self):
        for s in self.students:
            print(f"{s.name},{s.age},{s.score}")

    def sort(self):
        for s in sorted(self.students, key=lambda x: x.score, reverse=True):

test3 = StudentManager()
while True:
    c = input("1添加 2显示 3排序 4退出:")
    if c == "1":
        test3.add(input("姓名:"), input("年龄:"), input("成绩:"))
    elif c == "2":
        test3.show()
    elif c == "3":
        test3.sort()
    else:
        break

运行

相关推荐
Felven9 小时前
麒麟信安系统忘记root密码解决说明
linux·运维·服务器
qq5680180769 小时前
MySQL下载安装及配置
数据库·mysql
彭于晏Yan9 小时前
Springboot实现连接多个ElasticSearch数据库
数据库·spring boot·elasticsearch
IMPYLH9 小时前
Linux 的 base64 命令
linux·运维·服务器·bash·shell
qq_380651339 小时前
xu#True
python
程序员果子9 小时前
Nginx 从入门到精通:全面解析与实战指南
linux·运维·服务器·nginx
DeepModel9 小时前
【概率分布】均匀分布的原理、推导与Python实现
python·算法·概率论
light blue bird9 小时前
MES/ERP大数据报表条件索引查询组件
数据库·.net·winform·t-sql·大数据报表
wmfglpz889 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
m0_598177239 小时前
MYSQL order by , group by练习
数据库·mysql