Chinaunix首页 | 论坛 | 博客
  • 博客访问: 590711
  • 博文数量: 226
  • 博客积分: 10080
  • 博客等级: 上将
  • 技术积分: 1725
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-26 11:15
文章分类

全部博文(226)

文章存档

2011年(5)

2010年(64)

2009年(99)

2008年(37)

2007年(21)

我的朋友

分类: LINUX

2009-05-11 20:27:04

CSV全称为“Comma Separated Values”,是一种格式化的文件,由行和列组成,分隔符可以根据需要来变化。 
如下面为一csv文件:

Title,Release Date,Director
And Now For Something Completely Different,1971,Ian MacNaughton
Monty Python And The Holy Grail,1975,Terry Gilliam and 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

逐行处理:

for line in open("samples/sample.csv"):
    title, year, director = line.split(",")
    print year, title

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.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)
阅读(960) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~