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

运行

相关推荐
weixin_307779133 分钟前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
benchmark_cc3 分钟前
如何用 Python 计算盈亏痛苦比(Gain-to-Pain Ratio)?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
sbjdhjd3 分钟前
后端编程语言 PHP 笔记(第 1–3 章)|PHP 简介、版本与运行环境安装
开发语言·人工智能·笔记·后端·python·ai·php
新子-存在了11 分钟前
服务器中gitea
运维·服务器·gitea
tianyuanwo17 分钟前
PostgreSQL 系统操作手册
数据库·postgresql
Ivanqhz22 分钟前
wb 自动化搬运矩阵: 一条定型 “芯片选型偏好” 的话术?!
人工智能·python·机器学习
小白的高手之路23 分钟前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣
geovindu27 分钟前
python:DBSCAN
开发语言·后端·python·算法
lusklusklusk28 分钟前
SQL Server Replication请求订阅模式下的权限“黑盒子”:官方文档打架与实测结果
数据库
斯内普吖31 分钟前
(开源)智慧物业管理系统实战指南 基于 Python + Django + uni-app + Vue + MySQL
vue.js·python·django·uni-app·开源