【Python】建立CSV檔案
阿新 • • 發佈:2021-02-03
方法一:
通過pandas庫,根據已有資料建立CSV檔案;開啟Pycharm,輸入如下程式碼:
import pandas as pd #列表 a=[1,5,9] b=[2,6,10] c=[3,7,11] d=[4,8,12] e=['hello','world','foo'] #字典中的key值即為csv中的列名 frame = pd.DataFrame({'a':a,'b':b,'c':c,'d':d,'message':e}) #將DataFrame儲存為csv,index表識時候顯示行名,default=True frame.to_csv("ex1.csv",index=False,sep=',')
輸出結果:
方法二:
通過CSV庫,一行一行寫入,根據已有資料建立CSV檔案;在Pycharm,輸入如下程式碼:
import csv with open("ex2.csv","w") as csvfile: writer = csv.writer(csvfile) #先寫入columns_name writer.writerow(["a","b","c","d","message"]) writer.writerows([[1,2,3,4,'hello'],[5,6,7,8,'world'],[9,10,11,12,'foo']])
輸出結果: