![图片[1]-python如何读入csv文件-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5dc0d6f50f4f7176.gif)
最常用的一种方法,利用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学习网,免费的python学习网站,欢迎在线学习!
同样pandas也提供简单的读csv方法
importpandasaspd
data=pd.read_csv('test.csv')
另一种方法用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
importcsv
withopen("test.csv","r")ascsvfile:
reader=csv.reader(csvfile)
#这里不需要readlines
forlineinreader:
printline原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容