python寫入csv檔案的幾種方法總結

來源:互聯網
上載者:User

標籤:int   server   comment   .data   false   name   row   .com   lin   

最常用的一種方法,利用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=Truedataframe.to_csv("test.csv",index=False,sep=‘,‘)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
   a_name  b_name0       1       41       2       52       3       6
  • 1
  • 2
  • 3
  • 4

同樣pandas也提供簡單的讀csv方法

import pandas as pddata = pd.read_csv(‘test.csv‘)
  • 1
  • 2

會得到一個DataFrame類型的data,不熟悉處理方法可以參考pandas十分鐘入門

另一種方法用csv包,一行一行寫入

import csv#python2可以用file替代openwith 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_name0       1       31       2       32       3       4
  • 1
  • 2
  • 3
  • 4

讀取csv檔案用reader

import csvwith open("test.csv","r") as csvfile:    reader = csv.reader(csvfile)    #這裡不需要readlines    for line in reader:        print line

python寫入csv檔案的幾種方法總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.