Python CSV文件处理/读写
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)
二、使用csv模块处理(打印发行日期及标题):
import csv
reader = csv.reader(open("samples/sample.csv"))
for title, year, director in reader:
print(year, title)
2.1、改变分隔符,创建一csv.excel的子类,并修改分隔符为”;”
# File: csv-example-2.py
import csv
class SKV(csv.excel):
# like excel, but uses semicolons