当前位置: 首页 > 图灵资讯 > 行业资讯> python怎么写csv文件

python怎么写csv文件

发布时间:2025-05-08 10:44:31

使用pandas包最常用的方法之一。

importpandasaspd

#任意多组列表
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_nameb_name
014
125
236

相关推荐:Python入门教程

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

importpandasaspd
data=pd.read_csv('test.csv')

dataframe类型的data;

另一种方法是使用csv包,一行一行地写入。

importcsv

#python2可以用file代替open
withopen("test.csv","w")ascsvfile:
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]]
indexa_nameb_name
013
123
234

使用reader()方法读取csv文件

importcsv
withopen("test.csv","r")ascsvfile:
reader=csv.reader(csvfile)
#这里不需要readliness
forlineinreader:
printline

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09