Python如何读取txt文件中的元组列表并转换为自定义对象?
解决方案
一、快速修复当前TXT读写方案
你遇到的字符串转Python原生类型的问题,可以用Python标准库ast的literal_eval方法解决,该方法可以安全地将符合Python字面量格式的字符串转换为对应类型,不会有eval的安全风险。
写入代码优化
你原来的写入逻辑漏了第三项评分类别的输出,先修正:
def write_out(): # 用with上下文管理器自动关闭文件,避免资源泄露 with open('classes.txt', 'w', encoding='utf-8') as f_out: for course in classes: line = ','.join([ str(Course.course_name(course)), str(Course.credits(course)), str(Course.grading_categories(course)), # 补上评分类别字段 str(Course.assignments(course)) ]) + '\n' f_out.write(line)
读取代码实现
读取时用split的maxsplit参数限制分割次数,避免列表/元组内的逗号导致字段拆分错误:
import ast def read_in(): courses = [] with open('classes.txt', 'r', encoding='utf-8') as f_in: for line in f_in: line = line.strip() if not line: continue # 最多分割3次,把4个字段完整拆分 name, credits_str, categories_str, assignments_str = line.split(',', 3) # 类型转换 credits = int(credits_str) grading_categories = ast.literal_eval(categories_str) assignments_raw = ast.literal_eval(assignments_str) # 将作业元组转为Assignment对象 assignments = [Assignment(*item) for item in assignments_raw] # 实例化Course并加入列表 courses.append(Course(name, credits, grading_categories, assignments)) return courses
注意:该方案仅适用于课程名称不含逗号的场景,如果课程名可能出现逗号,不建议用CSV格式的TXT存储。
二、更适合结构化数据的通用存档方案
如果数据量较大、对象结构复杂,推荐使用以下两种更稳定的方案:
方案1:JSON序列化(推荐)
跨语言兼容、文件可读性高,适合大部分场景:
写入代码
import json def write_json(): data = [] for course in classes: data.append({ "name": Course.course_name(course), "credits": Course.credits(course), "grading_categories": Course.grading_categories(course), "assignments": [ {"name": a.name, "category": a.category, "score": a.score} for a in Course.assignments(course) ] }) with open("classes.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False)
读取代码
def read_json(): courses = [] with open("classes.json", "r", encoding="utf-8") as f: raw_data = json.load(f) for item in raw_data: assignments = [Assignment(a["name"], a["category"], a["score"]) for a in item["assignments"]] courses.append(Course( name=item["name"], credits=item["credits"], grading_categories=item["grading_categories"], assignments=assignments )) return courses
方案2:Pickle序列化(Python原生)
无需手动做类型转换,直接存储/读取完整Python对象,适合仅在Python程序内部使用的场景:
写入代码
import pickle def write_pickle(): with open("classes.pkl", "wb") as f: pickle.dump(classes, f)
读取代码
def read_pickle(): with open("classes.pkl", "rb") as f: return pickle.load(f)
注意:不要加载来源不明的pkl文件,存在执行恶意代码的安全风险,仅用于存储自己程序生成的存档。
内容的提问来源于stack exchange,提问作者Linus
相关产品推荐
相关产品推荐

