重写数据归集程序的代码

浏览: 1145

之前发的《python3解决excel多表格数据归集合并痛点,制作exe小程序分发使用》重新撰写了一次,

主要更新有

1、原来数据来源针对excel的xls xlsx文件,现在增加csv来源的相关参数

2、代码由来原来的脚本,封装到类中,并优化了性能,优化了代码简洁度,增加注释。(迭代方法、和字典的使用,)

3、对代码进行了性能测试,对数据来源为excel格式的60万行*37列数据 读取并写入需要10分钟,对数据来源为csv的60万行*37列数据 读取并写入约1分钟。excel需要整读比较消耗内存,读取缓慢,csv则非常快。

import csv
import os
from copy import copy
from glob import glob
from re import compile
import xlrd
class FileSum(object):
"""文件按列名进行聚合,目前支持xls xlsx csv编码格式文件格式"""
def get_porty(self):
'''获取配置文档内的参数'''
workbook = xlrd.open_workbook("配置文档.xlsx")
sheet1 = workbook.sheet_by_name("参数")
self.t = int(sheet1.cell_value(1, 1))
self.name_sheet = str(sheet1.cell_value(2, 1)).replace("*", "(.*)")#模糊匹配用的excel sheet名称
self.file_road = sheet1.cell_value(3, 1)#明细所在的路径
self.out_file = sheet1.cell_value(4, 1) # 输出的文件名
self.codetpye =sheet1.cell_value(5, 1)#csv读取的格式
self.row_list =workbook.sheet_by_name("表头放在一列注意不要空行").row_values(0) #需要获取的列名称
print('配置文档内的参数获取成功')

def get_filenames(self):
'''获取路径下面的对应的文件路径'''
excel_list= []
for filename in glob(self.file_road + "*." + "xls"):
excel_list.append(filename)
for filename2 in glob(self.file_road + "*." + "xlsx"):
excel_list.append(filename2)
csvf_list = []
for filename3 in glob(self.file_road + "*." + "csv"):
csvf_list.append(filename3)
return excel_list, csvf_list

def read_excel(self,excel):
'''读取excel对应列'''
workbook = xlrd.open_workbook(excel)
sheet_names = workbook.sheet_names()
pattern = compile(self.name_sheet)#正则表达式
a = 0
for i in sheet_names:
m = pattern.match(i)#正则表达式匹配sheet名称
if m and a == 0:
print("找到对应的数据为:",excel,"文件下" ,m.group(0))
sheet_name = m.group(0)
a = a + 1
elif a > 0:#找到一个后就停止
break
else:
continue
sheet1 = workbook.sheet_by_name(sheet_name)#打开sheet
'''转换成字典'''
ncols = sheet1.nrows # 获取列数
title_row = sheet1.row_values(self.t-1)
for j in range(self.t,ncols):
inf_row = sheet1.row_values(j)
d = dict(zip(title_row, inf_row))#列表转换为字典
yield d

def read_csv(self,csvfile):
'''读取csv对应列'''
if self.codetpye=='GBK' or self.codetpye== 'UTF-8' or self.codetpye=='Unicode':
code=self.codetpye
else:
code=None
f = open(csvfile, 'r',encoding=code)
print("找到csv文件源",csvfile)
csvf = csv.DictReader(f)
for i in csvf:
yield i
f.close()
def write_headrs(self):
'''如果不存在文件,则建立csv,并且填充表头'''
if os.path.exists(self.out_file):
print(8 * '*',"已经存在输出同名文件,进行续写",8 * '*')
else:
print(8 * '*', "创建文件进行写入", 8 * '*')
out = open(self.out_file, 'a', newline='')
csv_write = csv.writer(out, dialect='excel')
title=copy(self.row_list)
title.append("文件名")
csv_write.writerow(title)
out.close()
def write_next(self,content_list,file_name):
'''写入内容'''
out= open(self.out_file, 'a', newline='')
csv_write = csv.writer(out, dialect='excel')
for row in content_list:
next_row = []
for i in self.row_list:
r = row.get(i)
next_row.append(r)
if next_row.count(None)==len(next_row):
pass
else:
next_row.append(file_name)
csv_write.writerow(next_row)
out.close()

def file_into_csv(self):
'''写入流程集合'''
try:
self.get_porty()
self.write_headrs()
excel_list, csvf_list = self.get_filenames()
for csv in csvf_list:
c = self.read_csv(csv)
self.write_next(c, csv)
print(3 * '*', '%s写入成功' % csv, 3 * '*')
for excel in excel_list:
e = self.read_excel(excel)
self.write_next(e, excel)
print(3 * '*', '%s写入成功' % excel, 3 * '*')
print(8 * '*', ' 写入完成 ', 8 * '*')
except Exception as e:
print(e)
print('执行出错,请检查excel文件是否关闭,csv编码格式是否正确,文件是否正常')

if __name__ == '__main__':
FileSum().file_into_csv()
print("程序结束,有问题或者意见请加qq1085515834")

配置文档贴在附件里面

推荐 0
本文由 xinglipeng 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册