当前位置: 主页 > 日志 > Python >

Python - csv模块的DictReader与DictWriter类

import csv

FIELDS = ['Name', 'Sex', 'E-mail', 'Blog']

# DictWriter
csv_file = open('test.csv', 'wb')
writer = csv.DictWriter(csv_file, fieldnames=FIELDS)
# write header
writer.writerow(dict(zip(FIELDS, FIELDS)))

d = {}
d['Name'] = 'Qi'
d['Sex'] = 'Male'
d['E-mail'] = 'redice@163.com'
d['Blog'] = 'http://www.redicecn.com'

writer.writerow(d)
csv_file.close()
# For results, please see following picture

# DictReader
# A easier way for skipping the header
# Usually we need a extra flag variables
for d in csv.DictReader(open('test.csv', 'rb')):
    print d
# Output:
# {'Blog': 'http://www.redicecn.com', 'E-mail': 'redice@163.com', 'Name': 'Qi', 'Sex': 'Male'}

 

[日志信息]

该日志于 2012-02-17 11:33 由 redice 发表在 redice's Blog ,你除了可以发表评论外,还可以转载 “Python - csv模块的DictReader与DictWriter类” 日志到你的网站或博客,但是请保留源地址及作者信息,谢谢!!    (尊重他人劳动,你我共同努力)
   
验证(必填):   点击我更换验证码

redice's Blog  is powered by DedeCms |  Theme by Monkeii.Lee |  网站地图 |  本服务器由西安鲲之鹏网络信息技术有限公司友情提供

返回顶部