You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现学生对象信息逐行保存至TXT文件(支持原/新文件)需求

实现学生信息保存退出功能

首先先修正并补全你的Student类(原代码缺少语法冒号及实例属性赋值):

class Student:
    def __init__(self, first_name, last_name, ssn):
        self.first_name = first_name
        self.last_name = last_name
        self.ssn = ssn

接下来实现完整的save_and_exit函数,需要传入School类实例和原始文件路径,以便访问学生数据并处理保存逻辑:

def save_and_exit(school_instance, original_file):
    # 获取用户选择,循环确保输入有效
    while True:
        answer = input("Would you like to save to the original file or a new one? (original/new): ").strip().lower()
        if answer in ["original", "new"]:
            break
        print("请输入有效的选项:original 或 new")
    
    # 确定目标文件路径
    if answer == "original":
        target_file = original_file
    else:
        new_file = input("What is the name of the new file? ").strip()
        # 自动补充txt后缀(可选,可根据需求删除)
        if not new_file.endswith(".txt"):
            new_file += ".txt"
        target_file = new_file
    
    # 写入学生信息到文件
    try:
        with open(target_file, "w", encoding="utf-8") as f:
            # 遍历所有学生对象,按要求逐行写入属性
            for student in school_instance.students.values():
                f.write(f"{student.first_name}\n")
                f.write(f"{student.last_name}\n")
                f.write(f"{student.ssn}\n")
        print(f"信息已成功保存到 {target_file}")
    except Exception as e:
        print(f"保存失败:{str(e)}")
    
    # 退出程序
    exit()

关键逻辑说明

  • 输入校验:通过循环过滤无效输入,避免程序因错误输入中断
  • 文件处理:选择新文件时自动补充.txt后缀,减少用户输入负担(可按需移除)
  • 写入规则:用w模式覆盖写入文件,遍历School实例中所有学生,按要求将每个学生的名、姓、社保号各占一行保存
  • 异常捕获:处理保存时可能出现的IO错误,给出明确提示,避免程序直接崩溃

使用示例

当需要触发保存退出时,调用该函数并传入你的School实例和原始文件路径即可:

# 假设已创建school实例,原始文件路径为"students.txt"
save_and_exit(school, "students.txt")

内容的提问来源于stack exchange,提问作者Valdemar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:45:46