當前位置:成語大全網 - 新華字典 - 如何用python把list裏的數據寫入csv?

如何用python把list裏的數據寫入csv?

最常用的壹種方法,利用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=',')1234567891011

a_name ?b_name0 ? 1 ? 41 ? 2 ? 52 ? 3 ? 6

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

import pandas as pddata = pd.read_csv('test.csv')12

會得到壹個DataFrame類型的data。

另壹種方法用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]])12345678910

index ? a_name ?b_name0 ? 1 ? 31 ? 2 ? 32 ? 3 ? 41234

讀取csv文件用reader

import csvwith open("test.csv","r") as csvfile:

reader = csv.reader(csvfile) #這裏不需要readlines

for line in reader:

print line