csv(comma-separated values)是一種常見的資料儲存格式, 資料之間用特殊符號隔開,通常是用逗號隔開。Python有提供csv module讓使用者去讀寫csv格式的檔案, 非常的方便.

Return as list

# -*- coding: utf-8 -*-  

import csv  
f = open('example.csv', 'r')  
for row in csv.reader(f):  
    print row  
f.close()

Return as dictionary

# -*- coding: utf-8 -*-  

import csv  
f = open('example.csv', 'r')  
for row in csv.DictReader(f):  
    print row['column_name']  
f.close()

要把資料存成csv格式可以使用csv.writer(),以下是個簡單的範例:

Write into csv file

# -*- coding: utf-8 -*-  

import csv  
data = [['1', '2', '3', '4', '5', '6'], ['2', '3', '4', '5', '6', '7']]  
f = open("stock.csv","w")  
w = csv.writer(f)  
w.writerows(data)  
f.close() 

Write into csv file in dict format

# -*- coding: utf-8 -*-  

import csv  
writer = csv.writer(open('dict.csv', 'w'))
for key, value in mydict.items():
   writer.writerow([key, value])