python讀取CSV資料
CSV (逗號分隔值(Comma-Separated Values,CSV)檔案)(簡稱為 CSV)是指將資料列用逗號分隔的檔案。檔案的副檔名是 .csv。另一種資料型別,叫作製表符分隔值(tab-separated values,TSV)資料, 有時也與 CSV歸為一類。TSV 與 CSV 唯一的不同之處在於,資料列之間的分隔符是製表符(tab), 而不是逗號。檔案的副檔名通常是 .tsv,但有時也用 .csv 作為副檔名。從本質上來看, .tsv 檔案與 .csv 檔案在 Python 中的作用是相同的。
在文字編輯器中開啟 CSV 檔案,你看到的資料應該與其類似:
"Year","Country","Sex","Display Value","Numeric"
"1990","Andorra","Both sexes","77","77.00000"
"2000","Andorra","Both sexes","80","80.00000"
"2012","Andorra","Female","28","28.00000"
"2000","Andorra","Both sexes","23","23.00000"
"2012","United Arab Emirates","Female","78","78.00000"
"2000","Antigua and Barbuda","Male","72","72.00000"
"1990","Antigua and Barbuda","Male","17","17.00000"
"2012","Antigua and Barbuda","Both sexes","22","22.00000"
"2012","Australia","Male","81","81.00000"
下面用 Python (執行環境python2.7)開啟這個檔案,並將資料轉換成
Python 可以理解的格式。這隻要幾行程式碼:
1 import csv 2 csvfile = open('/home/lwk/python_test_data/data_processing/scores.csv', 'rb') 3 reader = csv.reader(csvfile) 4 for row in reader: 5 print row