原文地址:http://www.bugingcode.com/blog/python_csv.htmlhtml
csv 模塊被用來讀取CSV格式(用逗號分割數值)的數據文件,CSV格式的文件常常在微軟的Excel和其餘的程序中使用到。一個CSV文件常常包含一些行,每行包含一些列,列和列以前一般使用逗號分隔。python
以下的例子:編程
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
讀取這個文件,你但是簡單的循環每一行,使用split方法獲得每個單獨的列:函數
for line in open("samples/sample.csv"): title, year, director = line.split(",") print year, title
使用csv模塊取代這種方法,你能夠這樣寫:excel
import csv reader = csv.reader(open("samples/sample.csv")) for title, year, director in reader: print year, title
代碼以下:code
$ python csv-example-1.py Release Date Title 1971 And Now For Something Completely Different 1975 Monty Python And The Holy Grail 1979 Monty Python's Life Of Brian 1982 Monty Python Live At The Hollywood Bowl 1983 Monty Python's The Meaning Of Life
reader函數傳入一個序列或者是一個文件對象的迭代器,返回一個迭代器。htm
csv模塊的解析器不單單對字符串進行分割。他處理引用值和適當的行結束符,所以你可以讀入包含隨意的字符串(容許字符串包含逗號)。他也是能夠進行配置的,你能夠建立和註冊一個專有的描述符,用它去讀取不一樣的CSV特性。對象
以下的例子,介紹如何讀取瑞典變種的CSV,它使用分號取代了逗號進行分割。blog
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函數:教程
import csv reader = csv.reader(open("samples/sample.skv"), delimiter=";") for title, year, director in reader: print year, title
這個模塊一樣被用來建立CSV文件。writer函數建立CSV寫對象,它能夠方便的把數值轉換爲字符串,並在合適的位置跳出。
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) $ python csv-example-4.py 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
若是你有一個序列的數據(或者一個迭代器對象),你可使用writerows方法代替:
writer = csv.writer(sys.stdout) writer.writerows(data)
這個writer函數也支持不一樣的自定義格式。
轉載請標明來之:阿貓學編程
更多教程:阿貓學編程-python基礎教程