CSV 是(Comma Separated Values 逗号分隔值)的英文缩写,通常都是纯文本文件。这里介绍使用python 标准库读写csv 文件的方法。
python 提供了一个读写csv文件更强大的标准库:csv
逐行处理
1
2
3
for line in open("samples/sample.csv"):
title, year, director = line.split(",")
print year, title
使用csv模块处理
1
2
3
4
import csv
reader = csv.reader(open("samples/sample.csv"))
for title, year, director in reader:
print year, title
将数据存为CSV格式
通过 csv.writer
来生成一csv文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# coding: utf-8
import csv
import sys
items = [
("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 items:
writer.writerow(item)
例子
1
2
3
4
5
6
7
8
9
10
11
# coding: utf-8
import csv
with open( './data.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(['name', 'address', 'age'])
data = [
( 'xiaoming ','china','10'),
( 'Lily', 'USA', '12')]
writer.writerows(data)
f.close()
本文网址: https://pylist.com/topic/73.html 转摘请注明来源