python用字典形式写入csv文件

语法:csv.DicWriter(f):
写入时可使用writeheader()写入标题,然后使用writerow(字典格式数据行)或writerows(多行数据)

import csv

header = ['name','age']

data = [{'name':'suliang','age':'21'},
        {'name':'xiaoming','age':'22'},
        {'name':'xiaohu','age':'25'}]
with open ('information.csv','w',encoding='utf-8',newline='') as fp:
    # 写
    writer =csv.DictWriter(fp,header)
    # 写入标题
    writer.writeheader()
    # 将数据写入
    writer.writerows(data)