1. 程式人生 > 其它 >python—CSV的讀寫

python—CSV的讀寫

1.寫入csv資料

import csv

header=['class','name','sex','height','year']

rows=[

[1,'xiaoming','male',168,23],

[1,'xiaohong','female',162,22],

[2,'xiaozhang','female',158,21],

[2,'xiaoli','male',158,21]

]

with open('csvdir.csv','w',newline='')as f:          #newline=" "是為了避免寫入之後有空行

        ff=csv.writer(f)

        ff.writerow(header)

        ff.writerows(rows)

2.在寫入字典序列型別資料的時候,需要傳入兩個引數,一個是檔案物件——f,一個是欄位名稱——fieldnames,到時候要寫入表頭的時候,只需要呼叫writerheader方法,寫入一行字典系列資料呼叫writerrow方法,並傳入相應字典引數,寫入多行呼叫writerows

import csv

headers = ['class','name','sex','height','year']

rows = [

        {'class':1,'name':'xiaoming','sex':'male','height':168,'year':23},

        {'class':1,'name':'xiaohong','sex':'female','height':162,'year':22},

        {'class':2,'name':'xiaozhang','sex':'female','height':163,'year':21},

        {'class':2,'name':'xiaoli','sex':'male','height':158,'year':21},

    ]

with open('test2.csv','w',newline='')as f:

      f_csv = csv.DictWriter(f,headers)

      f_csv.writeheader()

      f_csv.writerows(rows)

注意:列表和字典形式的資料寫入是不一樣的!!!!!!

3.csv的讀取,和讀取檔案差不多:

import csv 

with open('test.csv')as f:

    f_csv = csv.reader(f)

    for row in f_csv:

        print(row)

參考:
作者:小二哥很二
連結:https://www.jianshu.com/p/ab49aecd9db2

[Haima的部落格] http://www.cnblogs.com/haima/