python读入csv文件的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

最常用的一种方法,利用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=Truedataframe.to_csv("test.csv",index=False,sep=',')

输出结果

a_nameb_name014125236

python学习网,免费的python学习网站,欢迎在线学习!

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

importpandasaspddata=pd.read_csv('test.csv')

另一种方法用csv包,一行一行写入

importcsv#python2可以用file替代openwithopen("test.csv","w")ascsvfile:writer=csv.writer(csvfile)#先写入columns_namewriter.writerow(["index","a_name","b_name"])#写入多行用writerowswriter.writerows([[0,1,3],[1,2,3],[2,3,4]])

输出结果

indexa_nameb_name013123234

读取csv文件用reader

importcsvwithopen("test.csv","r")ascsvfile:reader=csv.reader(csvfile)#这里不需要readlinesforlineinreader:printline

感谢各位的阅读!看完上述内容,你们对python读入csv文件的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。