python 标准库读写csv 文件

pylist 174

CSV 是(Comma Separated Values 逗号分隔值)的英文缩写,通常都是纯文本文件。
python 提供了一个读写csv文件更强大的库:csv

逐行处理:

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格式

通过csv.writer来生成一csv文件。

# 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)

例二

# 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()
登录发表评论

桂公网安备 45122402000014号