教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 python怎么写csv文件

python怎么写csv文件

发布时间:2021-04-13   编辑:jiaochengji.com
教程集为您提供python怎么写csv文件等资源,欢迎您收藏本站,我们将为您提供最新的python怎么写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=True
dataframe.to_csv("test.csv",index=False,sep=',')
 a_name  b_name
0       1       4
1       2       5
2       3       6

相关推荐:《Python入门教程

同样pandas也提供简单的读csv方法

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

会得到一个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]])
index   a_name  b_name
0       1      3
1       2      3
2       3      4

读取csv文件用reader()方法

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

您可能感兴趣的文章:
python以字典方式写入csv文件实现步骤
用python以字典方式写入csv文件实现操作
python怎么写csv文件
python怎么在csv中写入
python中怎么读取csv文件
python writerow乱码怎么解决
python保存文件后打不开的原因是什么
jQuery的CSV插件 jQuery CSV
php读取csv文件怎么去掉双引号
python读取csv出错怎么解决

[关闭]
~ ~