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
下一篇 python怎么运行cmd命令
