python写入csv文件的几种方法总结

生成test.csv文件

#coding=utf-
import pandas as pd #任意的多组列表
a = [,,]
b = [,,] #字典中的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_name  b_name

读取csv文件

#coding=utf-
import pandas as pd
data = pd.read_csv('test.csv')
print(data)

输出

C:\Users\macname\Desktop\t>python test.py
a_name b_name

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

#coding=utf-
import csv #python2可以用file替代open
with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile) #先写入columns_name
#写入多行用writerows
writer.writerows([["index","a_name","b_name"],[,,],[,,],[,,]])

内容为

index,a_name,b_name

,,

,,

,,

读取csv文件用reader

#coding=utf-
import csv
with open("test.csv","r") as csvfile:
reader = csv.reader(csvfile)
#这里不需要readlines
for line in reader:
print(line)

输出

C:\Users\macname\Desktop\t>python test.py
['index', 'a_name', 'b_name']
[]
['', '', '']
[]
['', '', '']
[]
['', '', '']
[]
上一篇:maven之pom


下一篇:11月29日 The Rails philosophy 完成rails on guide 的第一章getting started with rails