python如何处理csv类型文件
发布时间:2026-07-01 21:59:01

以下是处理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=True
dataframe.to_csv("test.csv",index=False,sep=',')输出结果
a_nameb_name 014 125 236
同样,pandas也提供了简单的csv阅读方法
importpandasaspd
data=pd.read_csv('test.csv')另一种方法是用csv包,一行一行地写入
importcsv
#openn2可以用file替换python2
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视频教程。
下一篇 python如何清空文件内容
