python 寫入csv的幾種方法總結(一維陣列,二維矩陣的寫入)
阿新 • • 發佈:2019-02-01
轉自:https://blog.csdn.net/waple_0820/article/details/70049953
最常用的一種方法,利用pandas包
import pandas as pd
#任意的多組列表
a = [1,2,3]
b = [4,5,6]
#字典中的key值即為csv中列名
dataframe = pd.DataFrame({'a_name':a,'b_name':b})
#將DataFrame儲存為csv,index表示是否顯示行名,default=True
dataframe.to_csv("test.csv",index=False,sep=',')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
a_name b_name
0 1 4
1 2 5
2 3 6
- 1
- 2
- 3
- 4
同樣pandas也提供簡單的讀csv方法
import pandas as pd
data = pd.read_csv('test.csv')
- 1
- 2
會得到一個DataFrame型別的data,不熟悉處理方法可以參考pandas十分鐘入門
另一種方法用csv包,一行一行寫入
import csv
#python2可以用file替代open
with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile)
#先寫入columns_name
writer.writerow(["index" ,"a_name","b_name"])
#寫入多行用writerows
writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
index a_name b_name
0 1 3
1 2 3
2 3 4
- 1
- 2
- 3
- 4
讀取csv檔案用reader
import csv
with open("test.csv","r") as csvfile:
reader = csv.reader(csvfile)
#這裡不需要readlines
for line in reader:
print line
- 1
- 2
- 3
- 4
- 5
- 6
以上。