python如何處理csv類型文件
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培訓機構:千鋒教育。

猜你喜歡LIKE
相關推薦HOT
更多>>
python中的filter函數功能是什么?
python中的filter函數功能是什么?在python中,面對眾多的數據,我們要過濾篩選出我們需要的數據。python中的filter函數就是起到了過濾篩選的作...詳情>>
2023-11-10 20:37:27
pythontime模塊是什么
pythontime模塊是什么在python中使用時間,就免不了和time模塊打交道,另外兩個模塊這個暫時先不做介紹。做time模塊的使用上,我們可以用它來對...詳情>>
2023-11-10 15:53:16
python是什么編程語言
python是什么編程語言1、說明是一種面向對象、解釋型計算機程序設計語言,由GuidovanRossum于1989年底發明,第一個公開發行版發行于1991年。Pyt...詳情>>
2023-11-10 15:21:05
python異常處理的兩種技巧
python異常處理的兩種技巧1、傳遞異常有時我們會在捕捉到一個異常后重新引發它(傳遞異常),實現起來很簡單,使用不帶參數的raise語句即可。deff...詳情>>
2023-11-10 14:49:39熱門推薦
python中的filter函數功能是什么?
沸python delattr函數如何使用?
熱python中pdb模塊怎么用?
熱Python如何截圖保存?
新python?中缺少module怎么辦?
python strftime和strptime的不同分析
python time.strptime的格式化
python中@contextmanager是什么?
python對象的三要素是什么
pythonGIL在Python多線程的應用
python如何對多個CSV文件進行讀取
pythonif嵌套命令如何理解?
python對列表進行永久性或臨時排序的方法
python生成器調用方法引發異常
技術干貨






