result = [(u'apple iOS', u'apple iOS', u'$400'),
(u'like new', u'5', u'$149'),
(u'apple iOS', u'apple iOS', u'$900'),
(u'excellent', u'6 Plus', u'$550'),
(u'like new', u'apple iOS', u'$279'),
(u'like new', u'4', u'$59')]
with open('data.csv', 'wb') as f:
for item in result:
line = ','.join(item) + '\n'
f.write(line.encode('utf-8'))
最常用的一种方法,利用pandas包
import pandas as pd#任意的多组列表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=',')1234567891011
a_name b_name0 1 41 2 52 3 6
同样pandas也提供简单的读csv方法,
import pandas as pddata = pd.read_csv('test.csv')12
会得到一个DataFrame类型的data。
另一种方法用csv包,一行一行写入
import csv
#python2可以用file替代open
with open("test.csv","w") as csvfile:
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]])12345678910
index a_name b_name0 1 31 2 32 3 41234
读取csv文件用reader
import csvwith open("test.csv","r") as csvfile:
reader = csv.reader(csvfile) #这里不需要readlines
for line in reader:
print line
外层 for 循环,内层 for 循环,tuple 强转 list 。当然也有其他方法实现 循环。
Python | 怎么读写csv文件
http://jingyan.baidu.com/article/f0e83a259f33c722e4910163.html