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

如何让Python程序正确找到目标CSV文件?

解决CSV文件找不到的问题
  • 核心问题:你写的路径"python projects/students.csv"是在当前程序目录下找名为python projects的子文件夹里的students.csv,但实际文件和程序在同一文件夹,根本不存在这个子目录,所以触发文件未找到(原英文提示‘file not found’的翻译)错误。

  • 修正路径:直接使用文件名即可,修改后的代码如下:

students = []

with open("students.csv") as file:
    for line in file:
        names, house = line.rstrip().split(',')
        student = {'name': names, 'house': house }
        students.append(student)

# 注意:字典不能直接排序,需指定排序依据的key
for student in sorted(students, key=lambda s: s['name']):
    print(f"{student['name']} is in {student['house']}")
  • 额外提醒:你原来的代码里for student in sorted(students)会报错,因为列表里的元素是字典,Python无法直接对字典排序,必须通过key参数指定按字典的某个字段(比如name)来排序,上面的代码已经修正了这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:52:06