import csv
file=r'd:/4.csv'
class CSV_Analyse:
def _read_csv (self,file):
reader =csv.reader(open(file,"rd"))
return [line for line in self.codes(reader)]
def codes(self,reader):
for line in reader:
yield[unicode(cell,'gb10830')for cell in line]
def result_list(self,file):
pm_call=[]
all_rows_no_title=self._read_csv(file)[1:] #如果不需要表头,可以用这行去掉;
#[1:]指从1开始内容,而不是从默认的0开始
for line in all_rows_no_title:
if "1" in line[2]:
pm_call.append([line[3],line[4],line[5]])
else:
other_call.append([line[8],line[9],line[10],line[11]])
return pm_call,other_call
>>> from pyExcelerator import *
>>> title=('time','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12')
>>> def creat_xls(call_tuple):
workbook=Workbook() #生产一个空的工作簿,名字为workbook
mingxi_sheet=workbook.add_sheet(u'频繁项目级')
for col_num,item in enumerate(title): #写入固定标题头
mingxi_sheet.write(0,col_num,item)
for row,line in enumerate(call_tuple[0]): #写入所需的内容
for col,item in enumerate(line[0:-1]):
mingxi_sheet.write(row+1,col,item)
for col_num in range(len(title)): #设置列的宽度
mingxi_sheet.col(col.num).width=5000
workbook.save('我的表格.xls')
>>> dealcall=CSV_Analyse() #生成类CSV_Analyse()的实例
>>> creat_xls(dealcall.result_list(file))
导入csv文件:
>>> import csv
>>> file =r'd:/4.csv'
>>> reader =csv.reader(open(file,"rd"))
>>> for line in reader:
print line
导入csv文件(除去第一行):
>>> import csv
>>> file = open(r'd:/4.csv')
>>> file.readline() #读掉第一行,下次引用file的时候将从第二行开始
>>> reader = csv.reader(file)
>>> for c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12 in reader:
print c12
导出csv文件:
import csv
writer = csv.writer(file('your.csv', 'wb'))
writer.writerow(['Column1', 'Column2', 'Column3'])
lines = [range(3) for i in range(5)]
for line in lines:
writer.writerow(line)