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输出格式
| filename | hologram_scores | hologram |
|---|---|---|
| img1.png | 0.0052322322 | False |
| img2.png | 0.00xxxxxx | False |
| img3.png | 0.0086543111 | False |
| img4.png | 0.0052331209 | True |
报错信息
NameError: name 'res' is not defined
需导出的字典打印结果
每次调用send_request_holo(imgpath)返回的字典格式如下:
{'hologram_scores': 0.0052322322, 'hologram': False}
解决思路
修复NameError错误:
原代码在循环前就使用了res变量,但此时res还未被赋值(res = send_request_holo(imgpath)是在循环里才执行的)。可以调整逻辑:要么先获取第一个文件的res来生成表头,要么直接写固定表头(比如['filename', 'hologram_scores', 'hologram'],因为字典的键是固定的)。解决类型拼接错误:
原代码用",".join()拼接时,res.values()里包含布尔值和浮点数,而join要求所有元素都是字符串,直接拼接会触发TypeError。需要把这些值转换成字符串,比如用str()处理每个值。更稳妥的方案:使用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
相关产品推荐
相关产品推荐

