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

如何将CSV文件的行转换为字典并保存到变量中?

解决方法

你可以创建一个列表来存储每一行的字典对象,把所有数据保存到变量里,不用直接打印。修改后的代码如下:

myFile = open('foo.csv', encoding='utf-8')
headers = next(myFile).rstrip().split(',')  # 获取表头
csv_data = []  # 用来存储所有行的字典
text = myFile.readline()
while text != "":
    row_dict = dict(zip(headers, text.rstrip("\n").split(",")))
    csv_data.append(row_dict)  # 将每一行的字典添加到列表中
    text = myFile.readline()  # 读取下一行

# 现在csv_data就是存储了所有数据的列表,你可以直接使用它
for item in csv_data:
    print(item)

要是需要单独访问某一行的字典,比如第一行,直接用csv_data[0]就行;遍历所有数据就用上面的循环操作。

另外,更规范的做法是用Python内置的csv模块,它能处理CSV里的特殊情况(比如字段包含逗号的情况),代码更健壮:

import csv

csv_data = []
with open('foo.csv', encoding='utf-8') as myFile:
    reader = csv.DictReader(myFile)
    for row in reader:
        csv_data.append(dict(row))  # 将每行的OrderedDict转为普通字典(可选)

# 输出结果
for item in csv_data:
    print(item)

这个方法不用手动处理表头和换行符,csv.DictReader会自动把每行数据映射成字典,键就是表头字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:42:26