python 读写CSV文件

CSV通常用于在电子表格软件和纯文本之间交互数据,CSV文件内容仅仅是一些用逗号分隔的原始字符串值。

以下示例获取数据,以CSV格式输出到文件中,然后将同样的数据读回,基于python2.7:

#!/usr/bin/env python

import csv
from distutils.log import warn as printf

DATA = (
    (9,'Web Clients and Servers','base64 urllib'),
    (10,'Web Programming:CGI & WSGI','cgi,time,wsgiref'),
    (13,'Web Services','urllib,twython'),
)

printf('*** WRITING CSV DATA')
f = open('bookdata.csv','w')
writer = csv.writer(f)
for record in DATA:
    writer.writerow(record)
f.close()

printf('*** REVIEW OF SAVED DATA')
f = open('bookdata.csv','r')
reader = csv.reader(f)
for chap,title,modpkgs in reader:
    printf('Chapter %s:%r(featuring %s)' % (chap,title,modpkgs))
f.close()


你可能感兴趣的:(python)