Python脚本无报错但无法将CSV保存至指定下载目录求助
问题排查与修复方案
核心问题1:函数未执行
你的脚本仅定义了create_customized_lesson_plan函数,但从未调用过它。代码逻辑根本没运行,自然不会生成任何文件。
核心问题2:数据提取逻辑错误
即使调用函数,当前代码也会因DataFrame切片的处理方式导致逻辑失效甚至隐性错误:
student_row是筛选后的DataFrame(哪怕只有一行),student_row["performance"]返回的是Series而非字典,直接用performance_data["math"]会索引失败;interests_data如果是字符串格式(如"math,science"),直接用"math" in interests_data会误匹配(比如包含"mathematics"也会被判定为包含"math"),如果是列表格式则需要先解析。
修复后的完整代码
import pandas as pd import numpy as np # 定义函数分析学生成绩、兴趣及学习风格 def create_customized_lesson_plan(student_id): # 从csv文件读取学生数据 student_data = pd.read_csv('/Users/jmeszaros/Downloads/student_data.csv') # 提取指定学生的相关数据:用iloc[0]取出单行数据(确保学生ID存在) student_row = student_data[student_data["student_id"] == student_id] if student_row.empty: print(f"学生ID {student_id} 不存在") return # 转换为单行Series,方便访问字段 student_info = student_row.iloc[0] # 假设performance是JSON格式字符串,先解析为字典 performance_data = eval(student_info["performance"]) if isinstance(student_info["performance"], str) else student_info["performance"] # 假设interests是逗号分隔的字符串,转换为列表 interests_data = student_info["interests"].split(",") if isinstance(student_info["interests"], str) else student_info["interests"] learning_style = student_info["learning_style"] # 分析数据确定学生的优势与兴趣 strengths = [] interests = [] if "math" in interests_data and performance_data.get("math", 0) > 80: strengths.append("math") if "science" in interests_data and performance_data.get("science", 0) > 80: strengths.append("science") if "history" in interests_data: interests.append("history") if "art" in interests_data: interests.append("art") # 根据学生优势与兴趣生成定制化课程计划 lesson_plan = [] if "math" in strengths: lesson_plan.append("Math game: Solve challenging math problems to earn points and unlock new levels") if "science" in strengths: lesson_plan.append("Science simulation: Explore the solar system and learn about the planets and their characteristics") if "history" in interests: lesson_plan.append("History quiz: Test your knowledge of historical events and figures") if "art" in interests: lesson_plan.append("Art project: Create your own masterpiece using different art materials and techniques") # 将课程计划转换为DataFrame lesson_plan_df = pd.DataFrame({"activity": lesson_plan}) # 打印保存路径,方便调试 save_path = f'/Users/jmeszaros/Downloads/lesson_plan_{student_id}.csv' print(f"正在保存文件到:{save_path}") # 将课程计划保存为csv文件 lesson_plan_df.to_csv(save_path, index=False) print("文件保存成功") # 必须调用函数!替换为实际存在的学生ID create_customized_lesson_plan("12345")
额外调试建议
- 检查
student_data.csv中是否存在你传入的student_id; - 如果生成的文件为空,说明
lesson_plan列表是空的,检查兴趣和成绩的判断逻辑; - 可以手动打印
save_path,然后直接在文件管理器中打开该路径,确认是否有文件生成。
内容的提问来源于stack exchange,提问作者Jonezy Meszaros
相关产品推荐
相关产品推荐

