Python讀取csv的常用方法
阿新 • • 發佈:2019-01-08
csv是Comma-Separated Values的縮寫,是用文字檔案形式儲存的表格資料,比如如下的表格:
假設上述csv檔案儲存為”A.csv”,利用Python自帶的csv模組,可以實現多種方式的讀取:
1.以行為單位儲存csv內容:
import csv
with open('A.csv','rb') as csvfile:
reader = csv.reader(csvfile)
rows= [row for row in reader]
print rows
得到
[['No.', 'Name', 'Age', 'Score'],
['1', 'Apple' , '12', '98'],
['2', 'Ben', '13', '97'],
['3', 'Celia', '14', '96'],
['4', 'Dave', '15', '95']]
2.讀取csv的某一列 (用列的序號):
import csv
with open('A.csv','rb') as csvfile:
reader = csv.reader(csvfile)
column = [row[2] for row in reader]
print column
得到
['Age', '12', '13', '14', '15']
3.讀取csv的某一行 (用行的序號):
import csv
with open('A.csv','rb') as csvfile:
reader = csv.reader(csvfile)
for i,rows in enumerate(reader):
if i == 2:
row = rows
print row
得到
['2', 'Ben', '13', '97']
4.使用字典儲存csv內容:
import csv
with open('A.csv','rb') as csvfile:
reader = csv.DictReader(csvfile)
column = [row for row in reader]
print column
得到
[{'Age': '12', 'No.': '1', 'Score': '98', 'Name': 'Apple'},
{'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'},
{'Age': '14', 'No.': '3', 'Score': '96', 'Name': 'Celia'},
{'Age': '15', 'No.': '4', 'Score': '95', 'Name': 'Dave'}]
5.讀取csv的某一列(用列的標題):
import csv
with open('A.csv','rb') as csvfile:
reader = csv.DictReader(csvfile)
column = [row['Age'] for row in reader]
print column
得到
['12', '13', '14', '15']
6.讀取csv的某一行(用行的標題):
import csv
with open('A.csv','rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row['Name']=='Ben':
print row
得到
{'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'}