第三次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

运行

相关推荐
cui_ruicheng28 分钟前
MySQL(四):数据类型与字段设计
数据库·mysql
皮皮学姐分享-ppx1 小时前
政府绿色采购数据库(2015-2024.3)
大数据·网络·数据库·人工智能·制造
珺毅同学1 小时前
YOLO生成预测json标签迁移问题
python·yolo·json
HackTwoHub1 小时前
最新Nessus2026.6.8版本主机漏洞扫描/探测工具Windows/Linux
linux·运维·服务器·安全·web安全·网络安全·安全架构
骑士雄师2 小时前
18.4 长期记忆可修改版
python
QWEDDRFTG2 小时前
C13/C19怎么选?服务器电源线电流与接口选型技巧
服务器
~小先生~2 小时前
Python从入门到放弃(一)
开发语言·python
天佑木枫2 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
闪电悠米3 小时前
黑马点评-Redis 消息队列-03_stream_consumer_group
开发语言·数据库·redis·分布式·缓存·junit·lua
Dust-Chasing3 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai