python處理csv類型文件的辦法:
下面講一下常見的幾種辦法處理csv文件:
最常用的一種方法,利用pandas包
importpandasaspd
#任意的多組列表
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=',')
輸出結果
a_nameb_name
014
125
236
同樣pandas也提供簡單的讀csv方法
importpandasaspd
data=pd.read_csv('test.csv')
另一種方法用csv包,一行一行寫入
importcsv
#python2可以用file替代open
withopen("test.csv","w")ascsvfile:
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]])
輸出結果
indexa_nameb_name
013
123
234
讀取csv文件用reader
importcsv
withopen("test.csv","r")ascsvfile:
reader=csv.reader(csvfile)
#這里不需要readlines
forlineinreader:
printline
以上內容為大家介紹了python如何處理csv類型文件,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。