Python將list元素轉(zhuǎn)存為CSV文件的實(shí)現(xiàn)
首先先定義一個(gè)list,將其轉(zhuǎn)存為csv文件,看將會(huì)報(bào)什么錯(cuò)誤
list=[[1,2,3],[4,5,6],[7,9,9]]list.to_csv(’e:/testcsv.csv’,encoding=’utf-8’)
運(yùn)行后出現(xiàn):
Traceback (most recent call last): File 'D:/Python/untitled/PcCVS.py', line 43, in <module> list.to_csv(’e:/testcsv.csv’,encoding=’utf-8’) AttributeError: ’list’ object has no attribute ’to_csv’
list沒(méi)有to_csv的屬性,也就是說(shuō)list直接是轉(zhuǎn)存不了為csv 為了解決這個(gè)問(wèn)題,我們可以引入panas模塊,使用其DataFrame屬性。
import pandas as pdlist=[[1,2,3],[4,5,6],[7,9,9]]# 下面這行代碼運(yùn)行報(bào)錯(cuò)# list.to_csv(’e:/testcsv.csv’,encoding=’utf-8’)name=[’one’,’two’,’three’]test=pd.DataFrame(columns=name,data=list)#數(shù)據(jù)有三列,列名分別為one,two,threeprint(test)test.to_csv(’e:/testcsv.csv’,encoding=’gbk’)
運(yùn)行結(jié)果為:
生成的csv文件為:
默認(rèn)的行名是從0開始遞增的數(shù)字,要是不喜歡這個(gè)表示,也可以自己改,改成自己喜歡的.只需要在pd.DataFrame()中定義一個(gè)index參數(shù),具體如下:
import pandas as pdlist=[[1,2,3],[4,5,6],[7,9,9]]name=[’one’,’two’,’three’]name2=[’a’,’b’,’c’]test=pd.DataFrame(columns=name,index=name2,data=list)print(test)test.to_csv(’e:/testcsv.csv’,encoding=’gbk’)
這樣就就修改好了
到此這篇關(guān)于Python將list元素轉(zhuǎn)存為CSV文件的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python list元素轉(zhuǎn)存為CSV內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python 如何在 Matplotlib 中繪制垂直線2. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼3. ASP常用日期格式化函數(shù) FormatDate()4. python中@contextmanager實(shí)例用法5. html中的form不提交(排除)某些input 原創(chuàng)6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. 如何通過(guò)python實(shí)現(xiàn)IOU計(jì)算代碼實(shí)例9. 開發(fā)效率翻倍的Web API使用技巧10. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式
