pyList

python 标准库读写CSV 文件

CSV 是(Comma Separated Values 逗号分隔值)的英文缩写,通常都是纯文本文件。这里介绍使用python 标准库读写csv 文件的方法。

python 标准库读写CSV 文件

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()
本文标签: CSV Python
本文网址: https://pylist.com/t/1427167461 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
发表第一条评论!
验证码图片
相关推荐