python爬虫怎么将字典保存为csv
可以,将 Python 字典保存为 CSV 文件的步骤:导入必要的库:import csv打开 CSV 文件以写入模式:with open('output.csv', 'w', newline='') as csvfile:创建 CSV 写入器对象:writer = csv.writer(csvfile)将字典的键作为 CSV 文件的标题行:header = list(my_dict.keys())逐行写入字典的值:for row in my_dict.values(): writer.wr
如何将 Python 字典保存为 CSV 文件
步骤:
导入必要的库:
import csv
打开 CSV 文件以写入模式:
立即学习“Python免费学习笔记(深入)”;
with open('output.csv', 'w', newline='') as csvfile:
创建 CSV 写入器对象:
writer = csv.writer(csvfile)
将字典的键作为 CSV 文件的标题行:
header = list(my_dict.keys())writer.writerow(header)
逐行写入字典的值:
for row in my_dict.values(): writer.writerow(row)
示例代码:
import csv# 定义一个带有键值对的字典my_dict = {'Name': ['Alice', 'Bob', 'Carol'], 'Age': [20, 25, 30]}# 将字典保存为 CSV 文件with open('people.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) header = list(my_dict.keys()) writer.writerow(header) for row in my_dict.values(): writer.writerow(row)