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

Python中使用csv DictWriter写入列表数据报错的原因与解决方法

解决csv.DictWriter写入CSV时的AttributeError问题

错误原因分析

你碰到的AttributeError: 'str' object has no attribute 'keys'其实很好理解:csv.DictWriter的writerow()方法必须接收一个字典作为参数,这个字典的键要和你定义的fieldnames一一对应。但你现在的代码里,循环遍历的是names列表里的单个元素(比如'kisha'、40000这类字符串/数字),这些单个值根本不是字典,自然没有keys()方法,所以触发了错误。

修复方案

根据你的数据情况,有两种合适的修复方式:

方案1:单条数据直接转字典

如果names只是单条员工的字段值,你可以用zip()把fieldnames和names的值配对成字典,不需要循环:

import csv
names = ['kisha' ,'smith' , 'kishasmith@gmail.com', 40000 , '1-1-2029' ,'janitor' ]
with open('employees.csv' , 'w', newline='')as employee_file:  # 加newline=''避免Windows下空行
    fieldnames2 = ['first' , 'last' , 'email' , 'salary' , 'DOB' , 'occupation']
    csvwriter = csv.DictWriter(employee_file , fieldnames = fieldnames2 , delimiter = ',')
    csvwriter.writeheader()
    # 把字段名和值配对成字典
    employee_data = dict(zip(fieldnames2, names))
    csvwriter.writerow(employee_data)

方案2:多数据场景用字典列表

如果之后要处理多条员工数据,建议直接把数据整理成字典列表的形式,这样循环写入更直观:

import csv
# 每条数据都是对应fieldnames的字典
employees = [
    {'first': 'kisha', 'last': 'smith', 'email': 'kishasmith@gmail.com', 'salary': 40000, 'DOB': '1-1-2029', 'occupation': 'janitor'},
    {'first': 'jane', 'last': 'doe', 'email': 'janedoe@example.com', 'salary': 45000, 'DOB': '3-3-2027', 'occupation': 'designer'}
]
with open('employees.csv' , 'w', newline='')as employee_file:
    fieldnames2 = ['first' , 'last' , 'email' , 'salary' , 'DOB' , 'occupation']
    csvwriter = csv.DictWriter(employee_file , fieldnames = fieldnames2 , delimiter = ',')
    csvwriter.writeheader()
    # 遍历字典列表写入每条数据
    for emp in employees:
        csvwriter.writerow(emp)

额外提示

打开文件时加上newline=''是Python官方文档推荐的写法,能避免Windows系统下写入CSV文件时出现多余的空行,提升兼容性。

内容的提问来源于stack exchange,提问作者Pha n texProgramming

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:28:08