一、需求分析
做这次脚本的初衷是为了从一个excel读取项目名称,并根据项目名称中的内容去匹配模板,如果项目中有新建则去匹配新建的模板某种匹配另一个模板,并将模板修改文件名为项目名称并重新改变目录,一下是代码实现
二、代码和注释
# -*- coding: utf-8 -*- import os, sys,re,shutil import xlrd dir=r'C:\Users\Administrator\Desktop\9.6\19年配网工程储备' #原文件存放的目录 #下面是两个模板第一个是新建模板,另一个是其他模板 xinjianfile=r'C:\Users\Administrator\Desktop\9.6\temp\徐州铜山10千伏大许镇机关南2#配变新建工程.xlsx' otherfile=r'C:\Users\Administrator\Desktop\9.6\temp\徐州铜山10千伏大许镇黄楼村4#配变增容改造工程.xlsx' save_path=r'C:\Users\Administrator\Desktop\9.6\changed'#修改后需要存放的目录 fs = os.listdir(dir)#列出该文件下所有文件,读取原文件夹下存放的excel文件 for f1 in fs: print('--------------current file to be make is %s ---------------' % f1) #因为以下文件有问题,需要用continue跳出循坏 if f1[0]=='~':continue if '单集' in f1 : continue #存放目录的子文件夹 tmp_path = os.path.join(dir,f1) save_file_path=save_path+'/'+f1+'/' if not os.path.exists(save_file_path): os.makedirs(save_file_path) work_book = xlrd.open_workbook(tmp_path) sheet0 = work_book.sheet_by_index(0)#读取改excel表中的第一个文件 col_values = sheet0.col_values(1) #读取改excel表中的第一个文件第二列,实际中第二列就是项目名称 colus=col_values[4:] #以为第二列前几个是无效信息用列表切片来跳过 i = 1 for f in colus: f=str(i)+'.'+f #这里给文件名加上标号 i+=1 #这里根据项目名称去匹配模板 if '新建' in f: new_filename=save_file_path+f+'.xlsx' shutil.copyfile(xinjianfile, new_filename) #复制excel文件并存储到相应目录 else: new_filename = save_file_path + f+'.xlsx' shutil.copyfile(otherfile, new_filename)