将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
相关产品推荐
相关产品推荐

