1. 程式人生 > >Python 寫入CSV檔案

Python 寫入CSV檔案

import csv
#CSV檔案的讀寫,想和pandas庫一起湊一篇文章
with open('data.csv','a+') as csvfile:
    fieldnames=['id','name','age']
    writer=csv.DictWriter(csvfile,fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'id':10001,'name':'xiaoli','age':20})
    writer.writerows([{'id':10002,'name':'xiaowang','age':21},{'id':10003,'name':'xiaozhang','age':21}])

with open('data.csv','r',encoding='utf-8') as  csva:
    read=csv.reader(csva)
    print(read)
    for row in read:
        print(row)