Python将list元素转存为CSV文件的实现
作者:那小子还在自学 时间:2022-03-14 20:15:00
首先先定义一个list,将其转存为csv文件,看将会报什么错误
list=[[1,2,3],[4,5,6],[7,9,9]]
list.to_csv('e:/testcsv.csv',encoding='utf-8')
运行后出现:
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没有to_csv的属性,也就是说list直接是转存不了为csv
为了解决这个问题,我们可以引入panas模块,使用其DataFrame属性。
import pandas as pd
list=[[1,2,3],[4,5,6],[7,9,9]]
# 下面这行代码运行报错
# list.to_csv('e:/testcsv.csv',encoding='utf-8')
name=['one','two','three']
test=pd.DataFrame(columns=name,data=list)#数据有三列,列名分别为one,two,three
print(test)
test.to_csv('e:/testcsv.csv',encoding='gbk')
运行结果为:
生成的csv文件为:
默认的行名是从0开始递增的数字,要是不喜欢这个表示,也可以自己改,改成自己喜欢的.只需要在pd.DataFrame()中定义一个index参数,具体如下:
import pandas as pd
list=[[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')
这样就就修改好了
来源:https://blog.csdn.net/qq_38268886/article/details/80744721
标签:Python,list,csv
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
ASP读取XML实例 优酷专辑采集程序 雷锋版
2011-03-08 11:05:00
django 实现编写控制登录和访问权限控制的中间件方法
2021-04-26 21:08:53
SQL注入攻击成为新威胁将挑战操作系统安全
2009-03-16 15:13:00
python Multiprocessing.Pool进程池模块详解
2023-08-25 09:24:59
python numpy中对ndarry按照index增删改查
2022-01-20 22:32:25
Python解析多帧dicom数据详解
2022-08-13 21:16:13
asp如何去除HTML标签
2010-06-07 20:47:00
Python OpenCV简单的绘图函数使用教程
2023-08-02 23:22:22
![](https://img.aspxhome.com/file/2023/7/61197_0s.jpg)
python实现简单的井字棋游戏(gui界面)
2023-03-06 23:16:01
![](https://img.aspxhome.com/file/2023/3/83973_0s.png)
Adobe发布Flash Player 10正式版
2008-10-15 17:15:00
[翻译]JavaScript中对象的层次与继承
2008-12-31 13:36:00
![](https://img.aspxhome.com/file/UploadPic/200812/31/cc-2-73s.png)
MySQL也能并发导入数据
2010-03-25 10:38:00
python中的各种运算符介绍
2021-08-09 12:49:04
![](https://img.aspxhome.com/file/2023/8/77618_0s.png)
MySQL常用维护管理工具
2009-03-08 16:51:00
![](https://img.aspxhome.com/file/UploadPic/20093/8/phpmyadmin-39s.jpg)
python logging日志打印过程解析
2023-11-03 13:04:09
![](https://img.aspxhome.com/file/2023/8/64308_0s.png)
讲解MySQL数据库的数据类型和建库策略
2008-12-17 14:39:00
python实现将视频按帧读取到自定义目录
2023-07-15 01:24:11
Oracle数据库安全策略分析(二)
2010-07-31 13:04:00
两种与SQL Server数据库交换数据的方法
2008-12-10 15:39:00
Python中FTP服务与SSH登录暴力破解的实现
2022-12-14 13:25:43
![](https://img.aspxhome.com/file/2023/4/75204_0s.png)