Python 的 CSV模块的使用方法,包括,reader, writer, DictReader, DictWriter.register_dialect
一直非常喜欢python的csv模块,简单易用,经常在项目中使用,现在举几个例子说明一下。
reader(csvfile[, dialect='excel'][, fmtparam])
参数表:
csvfile
需要是支持迭代(Iterator)的对象,并且每次调用next方法的返回值是字符串(string),通常的文件(file)对象,或者列表(list)对象都是适用的,如果是文件对象,打开是需要加"b"标志参数。
dialect
编码风格,默认为excel方式,也就是逗号(,)分隔,另外csv模块也支持excel-tab风格,也就是制表符(tab)分隔。其它的方式需要自己定义,然后可以调用register_dialect方法来注册,以及list_dialects方法来查询已注册的所有编码风格列表。
fmtparam
格式化参数,用来覆盖之前dialect对象指定的编码风格。
例子:
import csv
reader = csv.reader(file('your.csv', 'rb'))
for line in reader:
print line
writer(csvfile[, dialect='excel'][, fmtparam])
参数表(略: 同reader, 见上)
例子:
import csv writer = csv.writer(file('your.csv', 'wb')) writer.writerow(['Column1', 'Column2', 'Column3']) lines = [range(3) for i in range(5)] for line in lines: writer.writerow(line)
1. 写入并生成csv文件
代码:
# coding: utf-8
import csv
csvfile = file('csv_test.csv', 'wb')
writer = csv.writer(csvfile)
writer.writerow(['姓名', '年龄', '电话'])
data = [
('小河', '25', '1234567'),
('小芳', '18', '789456')
]
writer.writerows(data)
csvfile.close()
-
wb中的w表示写入模式,b是文件模式
-
写入一行用writerow
-
多行用writerows
2. 读取csv文件
代码:
# coding: utf-8
import csv
csvfile = file('csv_test.csv', 'rb')
reader = csv.reader(csvfile)
for line in reader:
print line
csvfile.close()
运行结果:
root@he-desktop:~/python/example# python read_csv.py
['\xe5\xa7\x93\xe5\x90\x8d', '\xe5\xb9\xb4\xe9\xbe\x84', '\xe7\x94\xb5\xe8\xaf\x9d']
['\xe5\xb0\x8f\xe6\xb2\xb3', '25', '1234567']
['\xe5\xb0\x8f\xe8\x8a\xb3', '18', '789456']
打印发行日期及标题,逐行处理:
for line in open("samples/sample.csv"): title, year, director = line.split(",") print year, title
使用csv模块处理:
import csv reader = csv.reader(open("samples/sample.csv")) for title, year, director in reader: print year, title
改变分隔符
创建一csv.excel的子类,并修改分隔符为”;”
# File: csv-example-2.py import csv class SKV(csv.excel): # like excel, but uses semicolons delimiter = ";" csv.register_dialect("SKV", SKV) reader = csv.reader(open("samples/sample.skv"), "SKV") for title, year, director in reader: print year, title
如果仅仅仅是改变一两个参数,则可以直接在reader参数中设置,如下:
# File: csv-example-3.py import csv reader = csv.reader(open("samples/sample.skv"), delimiter=";") for title, year, director in reader: print year, title
将数据存为CSV格式
通过csv.writer来生成一csv文件。
# File: csv-example-4.py import csv import sys data = [ ("And Now For Something Completely Different", 1971, "Ian MacNaughton"), ("Monty Python And The Holy Grail", 1975, "Terry Gilliam, Terry Jones"), ("Monty Python's Life Of Brian", 1979, "Terry Jones"), ("Monty Python Live At The Hollywood Bowl", 1982, "Terry Hughes"), ("Monty Python's The Meaning Of Life", 1983, "Terry Jones") ] writer = csv.writer(sys.stdout) for item in data: writer.writerow(item)