python读写csv文件(带标题内容)
什么是csv逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)
以下代码为python2.7下编写并运行,WIN10下测试通过。
写入CSV文件: - # coding:utf-8
- import csv
- data = [
- {'id':'123','name':'anjing','age':'26'},
- {'id':'1234','name':'anjing1','age':'27'},
- {'id':'12345','name':'anjing2','age':'28'},
- {'id':'123567','name':'anjing3','age':'29'}
- ]
- with open('123.csv','wb') as f:
- fieldnames = {'id','name','age'}
- writer = csv.DictWriter(f,fieldnames=fieldnames)
- writer.writeheader()
- for i in data:
- writer.writerow(i)
复制代码写入后的内容如下:
|