Python 中 CSV 文件与字典列表之间的转换
约 55 个字 34 行代码 预计阅读时间 1 分钟
CSV 转字典列表
方法 1
| import csv
def read_csv_to_dict_list(file_path, **kwargs):
with open(file_path, 'r', **kwargs) as f:
reader = csv.DictReader(f)
return [row for row in reader]
|
方法 2
| import csv
def read_csv_to_dict_list(file_path, **kwargs):
f = open(file_path, 'r', **kwargs)
csv_reader = csv.reader(f)
csv_list = list(csv_reader)
ret_list = []
for col in csv_list[1:]:
col_zip = zip(csv_list[0], col)
ret_list.append(dict(col_zip))
return ret_list
|
字典列表转 CSV
| def dict_list_to_csv(dict_list: list[dict], file_path: str, **kwargs):
"""
将字典列表转换为 CSV 文件
:param dict_list: 字典列表
:param file_path: CSV 文件路径
:param kwargs: 传递给 open() 的其他参数(如编码方式)
"""
fieldnames = dict_list[0].keys()
with open(file_path, 'w', newline='', **kwargs) as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for row_dict in dict_list:
write_row = row_dict.copy()
writer.writerow(write_row)
|