csv是comma-separated values的縮寫,是用文字檔案形式儲存的**資料,比如如下的**:
就可以儲存為csv檔案,檔案內容是:
no.,name,age,score假設上述csv檔案儲存為"test.csv"1,mayi,18,99
2,jack,21,89
3,tom,25,95
4,rain,19,80
如何用python像操作excel一樣提取其中的一列,即乙個字段,利用python自帶的csv模組,有兩種方法可以實現:
#得到:!/usr/bin/python3
#-*- coding:utf-8 -*-
__author__ = '
mayi
'import
csv#
讀with open("
test.csv
", "
r", encoding = "
utf-8
") as f:
reader =csv.reader(f)
rows = [row for row in
reader]
print(rows)
[['要提取其中某一列,可以用下面的**:no.', '
name
', '
age', '
score'],
['1', '
mayi
', '
18', '99'
], ['2
', '
jack
', '
21', '89'
], ['3
', '
tom', '
25', '95'
], ['4
', '
rain
', '
19', '
80']]
#得到:!/usr/bin/python3
#-*- coding:utf-8 -*-
__author__ = '
mayi
'import
csv#
讀取第二列的內容
with open("
test.csv
", "
r", encoding = "
utf-8
") as f:
reader =csv.reader(f)
column = [row[1] for row in
reader]
print(column)
['注意從csv讀出的都是str型別。這種方法要事先知道列的序號,比如name在第2列,而不能根據'name'這個標題查詢。這時可以採用第二種方法:name
', '
mayi
', '
jack
', '
tom', '
rain
']
#得到:-*- coding:utf-8 -*-
__author__ = '
mayi
'import
csv#
讀with open("
test.csv
", "
r", encoding = "
utf-8
") as f:
reader =csv.dictreader(f)
column = [row for row in
reader]
print(column)
[,如果我們想用dictreader讀取csv的某一列,就可以用列的標題查詢:, ,]
#得到:!/usr/bin/python3
#-*- coding:utf-8 -*-
__author__ = '
mayi
'import
csv#
讀取name列的內容
with open("
test.csv
", "
r", encoding = "
utf-8
") as f:
reader =csv.dictreader(f)
column = [row['
name
'] for row in
reader]
print(column)
['讀檔案時,我們把csv檔案讀入列表中,寫檔案時會把列表中的元素寫入到csv檔案中。mayi
', '
jack
', '
tom', '
rain
']
#得到:!/usr/bin/python3
#-*- coding:utf-8 -*-
__author__ = '
mayi
'import
csv#
寫:追加
row = ['
5', '
hanmeimei
', '
23', '81'
]out = open("
test.csv
", "
a", newline = ""
)csv_writer = csv.writer(out, dialect = "
excel")
csv_writer.writerow(row)
使用Python對Csv檔案操作
就可以儲存為csv檔案,檔案內容是 no.name,age,score 1,mayi,18,99 2,jack,21,89 3,tom,25,95 4,rain,19,80 假設上述csv檔案儲存為 test.csv 如何用python像操作excel一樣提取其中的一列,即乙個字段,利用python...
使用Python對Csv檔案操作
csv是comma separated values的縮寫,是用文字檔案形式儲存的 資料,比如如下的 就可以儲存為csv檔案,檔案內容是 no.name,age,score 1,mayi,18,99 2,jack,21,89 3,tom,25,95 4,rain,19,80 假設上述csv檔案儲存為...
python使用csv寫入csv檔案
沒什麼好說的,直接上 吧 with open file.csv w encoding utf 8 newline as csvfile writer csv.writer csvfile 首先是表頭 writer.writerow id name gender birthday rating 然後是...