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

Python新手求助:字典数据导出CSV报错,求解决方案

字典转CSV文件报错求助

我是Python新手,尝试把字典结果保存到CSV文件时遇到错误,搜了类似案例还是解决不了。下面是我的代码、期望的CSV输出格式、报错信息和字典打印结果,求解决思路。

我的代码

with open('hologram.csv','w') as f: 
    f.write(",".join(['filename'] + [*res]) + "\n") 
for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
    res = send_request_holo(imgpath)
    f.write(",".join([os.path.basename(imgpath)] + [*res.values()]) + "\n")  
    print(res)

期望的CSV输出格式

filenamehologram_scoreshologram
img1.png0.0052322322False
img2.png0.00xxxxxxFalse
img3.png0.0086543111False
img4.png0.0052331209True

报错信息

NameError: name 'res' is not defined

需导出的字典打印结果

每次调用send_request_holo(imgpath)返回的字典格式如下:

{'hologram_scores': 0.0052322322, 'hologram': False}

解决思路

  1. 修复NameError错误:
    原代码在循环前就使用了res变量,但此时res还未被赋值(res = send_request_holo(imgpath)是在循环里才执行的)。可以调整逻辑:要么先获取第一个文件的res来生成表头,要么直接写固定表头(比如['filename', 'hologram_scores', 'hologram'],因为字典的键是固定的)。

  2. 解决类型拼接错误:
    原代码用",".join()拼接时,res.values()里包含布尔值和浮点数,而join要求所有元素都是字符串,直接拼接会触发TypeError。需要把这些值转换成字符串,比如用str()处理每个值。

  3. 更稳妥的方案:使用Python内置的csv模块:
    手动拼接CSV容易出现格式问题(比如内容里有逗号的情况),用csv.DictWriter可以自动处理这些问题,代码更健壮。示例代码如下:

    import csv
    import glob
    import os
    
    # 固定表头,和字典的键对应
    fieldnames = ['filename', 'hologram_scores', 'hologram']
    
    with open('hologram.csv', 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()  # 写入表头
        for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
            res = send_request_holo(imgpath)
            # 把文件名加入字典,然后写入一行
            row_data = {'filename': os.path.basename(imgpath), **res}
            writer.writerow(row_data)
            print(res)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:20:54