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

将Python打印内容重定向至CSV文件报错求助

解决CSV写入时的TypeError问题并实现输出内容写入CSV

问题根源

你遇到的TypeError: list indices must be integers or slices, not tuple错误,是因为定义rows列表时犯了一个基础语法错误:各个子列表之间没有用逗号分隔。Python会把连续的两个列表表达式(比如["a"] ["b"])错误地解析为「用第二个列表作为第一个列表的索引」,这显然不符合逻辑,所以抛出了类型错误。

修正后的完整代码

下面是修复后的代码,同时我还优化了几个细节(比如避免CSV空行、路径写法更安全):

import statistics
import csv

# 假设numberList已经被正确定义并赋值了数据
numberList = [30, 45, 60, 35, 50]  # 示例数据,你可以替换成自己的实际数据

# 修正:子列表之间添加逗号
rows = [ 
    ["La moyenne de frameRate est :", statistics.mean(numberList), "FPS"],
    ["Le frame rate max est:", max(numberList), "FPS"],
    ["Le FrameRate minimum est:", min(numberList), "FPS"],
    ["L'ecart type des FrameRate est:", statistics.stdev(numberList), "FPS"]
]

# 用newline=''避免写入后出现多余空行,用原始字符串路径避免转义问题
with open(r"C:\Users\skehal\Desktop\doc.csv", 'w', newline='', encoding='utf-8') as csvfile:
    csv_writer = csv.writer(csvfile)
    for row in rows:
        csv_writer.writerow(row)

# 保留你的控制台输出
print("La moyenne de FrameRate est :" , statistics.mean(numberList), "FPS")
print("Le frame rate max est:", max(numberList), "FPS")
print("Le FrameRate minimum est:", min(numberList), "FPS")
print("L'ecart type des FrameRate est:", statistics.stdev(numberList), "FPS")

关键修复与优化说明

  • 添加子列表间的逗号:这是解决TypeError的核心,让Python正确识别rows是包含多个子列表的列表
  • 导入必需模块:确保导入statistics和csv模块,否则会报NameError
  • 使用newline=''参数:这是csv模块官方推荐的写法,能避免在Windows系统下写入CSV时出现多余的空白行
  • 原始字符串路径:用r"路径"的写法,不需要手动转义反斜杠,更安全不易出错
  • 指定编码为utf-8:避免写入非ASCII字符(比如法语的特殊字符)时出现乱码问题

运行修正后的代码,你的控制台输出内容就会正确写入到指定路径的CSV文件中,同时控制台也会正常打印统计结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:16:02