跳至内容
Python 俱乐部
用户工具
登录
站点工具
搜索
工具
显示页面
修订记录
反向链接
最近更改
媒体管理器
网站地图
登录
>
最近更改
媒体管理器
网站地图
您的足迹:
python-files:csv
本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。
====== Python CSV文件处理/读写 ====== CSV全称为“Comma Separated Values",是一种格式化的文件,由行和列组成,分隔符可以根据需要来变化。 \\ 如下面为一csv文件: <file> 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 </file> ===== 打印发行日期及标题。===== 逐行处理: <code python> for line in open("samples/sample.csv"): title, year, director = line.split(",") print year, title </code> =====使用csv模块处理:===== <code python> import csv reader = csv.reader(open("samples/sample.csv")) for title, year, director in reader: print year, title </code> =====改变分隔符===== 创建一csv.excel的子类,并修改分隔符为";" <code python> # 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 </code> 如果仅仅仅是改变一两个参数,则可以直接在reader参数中设置,如下: <code python> # File: csv-example-3.py import csv reader = csv.reader(open("samples/sample.skv"), delimiter=";") for title, year, director in reader: print year, title </code> ===== 将数据存为CSV格式 ===== 通过csv.writer来生成一csv文件。 <code python> # 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) </code>
python-files/csv.txt
· 最后更改: 2010/06/02 01:18 (外部编辑)
页面工具
显示页面
修订记录
反向链接
回到顶部