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

Python中如何用OrderedDict写入CSV?代码提示不可写入问题求解

代码问题分析与修正

存在的问题

  • 文件打开模式错误:写入文件时,open()默认使用只读模式('r'),没有写入权限,这是报错“文件不可写入”的直接原因。需要改为写入模式(如'w'覆盖写入、'a'追加写入),同时建议指定编码encoding='utf-8'避免乱码。
  • 路径转义字符冲突:Windows路径中的反斜杠\会被Python解析为转义字符(比如\l、\p),可能导致路径识别错误。解决方法是使用原始字符串(路径前加r),或把反斜杠替换为正斜杠/。
  • writerows参数错误:直接传入person_mean只会写入字典的键,无法输出姓名和平均分的对应关系。需要传入person_mean.items(),它会生成包含键值对的元组迭代器,符合csv.writer.writerows()的输入要求。
  • 缺少必要导入:代码中使用了mean()函数,但未导入statistics模块,运行时会抛出NameError;同时OrderedDict也需要从collections模块导入。

修正后的代码

from statistics import mean
from collections import OrderedDict
import csv

# 读取文件:用原始字符串处理路径,指定编码
with open(r'F:\learning\coding\python learning\jadi excersisse\work with files\grades_for_exercise.csv', encoding='utf-8') as f:
    myFile = csv.reader(f)
    person_mean = OrderedDict()
    for row in myFile:
        name = row[0]
        person_grades = []
        for number in row[1:]:
            person_grades.append(int(number))
        person_mean[name] = mean(person_grades)
    print(list(person_mean.items()))

# 写入文件:指定写入模式、编码,添加newline避免Windows下空行
with open(r'F:\learning\coding\python learning\jadi excersisse\work with files\one_result.csv', 'w', newline='', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    # 可选:写入表头
    # csvwriter.writerow(['姓名', '平均分'])
    csvwriter.writerows(person_mean.items())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:22:15