功能:
把文件夹内的图片文件进行重命名,并压缩成一个zip文件,如果文件数过多会自动分开压缩处理
生成文件格式如下图:
import os import random import shutil import zipfile from openpyxl import Workbook image_path = r'F:\新建文件夹\Images' dir_name = '照片模板' faceNums = 0 # 第一步获取目录图片文件名 def getImagesFilename(filepath): global faceNums ''' 函数功能:获取某目录下所有图片文件名 ''' flists = [] if not os.path.isdir(filepath): print(f'{filepath}不是目录') return dirs = os.listdir(filepath) for file in dirs: if file.endswith('.jpg') or file.endswith('png') or file.endswith('bmp'): faceNums += 1 flists.append(file) return flists def createModelDir(): d = os.path.join(os.path.dirname(image_path), dir_name) if os.path.exists(d): shutil.rmtree(d) os.mkdir(d) def createPhone(): phone = '' num1 = random.choice(['123', '124', '125', '126', '127', '128', '129', '130']) phone += str(num1) for i in range(0,8): num = random.randint(0,9) phone += str(num) return phone def createDatas(filename): phonelist = [] for file in filename: phone = createPhone() while phone in phonelist: phone = createPhone() phonelist.append(phone) filename, extentsion = os.path.splitext(file) src = os.path.join(image_path, file) dst = os.path.join(os.path.dirname(image_path),dir_name, phone + extentsion) shutil.copyfile(src, dst) def autoZip(): d1 = os.path.join(os.path.dirname(image_path), dir_name) for dirpath, dirnames, filenames in os.walk(d1): print(len(filenames)) target = 3000 zlist = [] for i in range((int(len(filenames)) // target) + 1): d = os.path.join(os.path.dirname(image_path), dir_name + '_' + str(i) + '.zip') z = zipfile.ZipFile(d, 'w', zipfile.ZIP_DEFLATED) zlist.append(z) num = 0 for dirpath, dirnames, filenames in os.walk(d1): for filename in filenames: absname = os.path.join(dirpath, filename) arcname = absname[len(os.path.abspath(d1)) + 1:] # 加参数arcname,压缩不带目录层级 zpos = (num // target) + 1 zlist[zpos-1].write(absname, arcname) num += 1 for j in zlist: j.close() def writeXlsx(): wb = Workbook() ws = wb.active d1 = os.path.join(os.path.dirname(image_path), dir_name) dirs = os.listdir(d1) name = 2500 data = [] data.append(['姓名', '性别', '身份', '手机号', '证件类型', '证件号', '门禁卡id(少于20位数字)', '学历', '政治面貌', '紧急联系人', '紧急联系人号码', '是否为本地户籍', '帮扶类型', '楼栋', '单元', '门牌号']) for file in dirs: name = name + 1 sex = '女' role = '其他' filename, extentsion = os.path.splitext(file) position_lou = '6号楼' position_unit = '1单元' postion_door = '605' person = [name, sex, role, filename, '', '', '', '', '', '', '', '', '', position_lou, position_unit, postion_door] data.append(person) for row in range(5, len(data)+5): for col in range(1, 17): ws.cell(row, col, data[row-5][col-1]) wb.save(os.path.join(os.path.dirname(image_path), dir_name + '.xlsx')) if __name__ == '__main__': r = getImagesFilename(image_path) createModelDir() createDatas(r) autoZip() writeXlsx() print(f'图片总数:{faceNums}')