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

使用Python csv模块writerows()时触发TypeError的问题求助

错误分析与解决:csv.writerows()触发TypeError

错误原因

  1. 方法使用错误:csv.writer.writerows()要求传入可迭代的行集合(例如列表套列表,每个子列表代表一行数据),但你在循环中传入的loanList[i]是单个整数,不属于可迭代结构,直接触发TypeError。
  2. 数据结构不匹配:你的表头包含Name和Results两列,但loanList仅存储了月供的数值,没有对应Name列的内容,写入后csv格式会和表头不匹配。
  3. 遍历逻辑冗余:通过range(len(loanList))按索引遍历的方式没必要,直接遍历列表元素更简洁。

解决方案

  1. 将writerows()替换为writerow():后者用于写入单行数据,接受单个列表/元组作为参数。
  2. 调整loanList的存储结构,每个元素改为包含测试项名称和月供数值的子列表,匹配表头的列数。
  3. 使用with语句管理文件,自动处理文件的打开和关闭,避免资源泄漏。
  4. 简化循环,直接遍历loanList的元素进行写入。

修正后的完整代码

import csv

header = ['Name','Results']
a = 10000
b = [0.032,0.043,0.037,0.043,0.044,0.029,0.028,0.030]
c = [6,7,4,3,4,6,7,9]

loanList = []

def monthlyRepayment(principalAmount, interest, year):
    for idx in range(len(interest)):
        finalAmount = principalAmount * ((1 + interest[idx]) ** year[idx])
        monthlyAmount = finalAmount / (year[idx] * 12)
        # 存储为包含名称和结果的子列表
        loanList.append([f"测试项{idx+1}", round(monthlyAmount)])
        print(round(monthlyAmount))

monthlyRepayment(a, b, c)

# 使用with语句管理文件
with open("loanResults.csv", "w", newline="") as file:
    db = csv.writer(file)
    db.writerow(header)
    # 直接遍历loanList写入每行
    for row in loanList:
        db.writerow(row)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:45:50