将嵌套字典写入CSV文件可以通过以下步骤实现:
import csv
data = [
{"Name": "John", "Age": 28, "Country": "USA"},
{"Name": "Emma", "Age": 32, "Country": "Canada"},
{"Name": "Sophia", "Age": 25, "Country": "UK"}
]
csv_file = "data.csv"
fields = ["Name", "Age", "Country"]
DictWriter
类将嵌套字典数据写入CSV文件。with open(csv_file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
writer.writerows(data)
完整代码示例:
import csv
data = [
{"Name": "John", "Age": 28, "Country": "USA"},
{"Name": "Emma", "Age": 32, "Country": "Canada"},
{"Name": "Sophia", "Age": 25, "Country": "UK"}
]
csv_file = "data.csv"
fields = ["Name", "Age", "Country"]
with open(csv_file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
writer.writerows(data)
以上代码将会创建一个名为"data.csv"的CSV文件,并将嵌套字典数据写入其中。CSV文件内容如下:
Name,Age,Country
John,28,USA
Emma,32,Canada
Sophia,25,UK
推荐的腾讯云相关产品:腾讯云对象存储(COS),用于存储和管理CSV文件。产品介绍链接地址:https://cloud.tencent.com/product/cos
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云