python怎么在csv中写入
发布时间:2025-03-07 22:13:50

使用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
同样,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
读取csv文件使用reader
importcsv
withopen("test.csv","r")ascsvfile:
reader=csv.reader(csvfile)
#这里不需要readliness
forlineinreader:
printlinepython培训视频众多,全部在python学习网,欢迎在线学习!
下一篇 python中根号怎么输入
