python合并同系列PDF,并保持路径结构不变
以下python文件放到D盘根目录运行,会在D盘自动生成“合并后”文件夹,并且合成的pdf所在的路径结构不改变。
思路:先创建“合并后”里的子文件夹,然后才开始合成pdf,合成后的pdf保存到对应的子文件夹中,单独的pdf也会放到里面(自我合成)。
pyton代码:
import os import re import PyPDF2 basedir = ".\\合并前" cls_list = [] for dirs in os.listdir(basedir): print(dirs) os.makedirs('.\\合并后\\'+dirs) cls_dict = {} for i, name in enumerate(os.listdir(os.path.join(basedir, dirs))): filepath = os.path.join(basedir,dirs, name) # print(name) f = name.split('.')[0].split("_")[-1] key = "".join(re.findall("\D", f)) if key not in cls_dict.keys(): cls_dict[key] = [] cls_dict[key].append(filepath) else: cls_dict[key].append(filepath) cls_list.append(cls_dict) for s in cls_list: for k,v in s.items(): print(k) print(v) # merge the file. opened_file = [open(file_name, 'rb') for file_name in v] print('[]', opened_file) pdfFM = PyPDF2.PdfFileMerger() for file in opened_file: pdfFM.append(file) # output the file. with open(".\\合并后"+v[0][5:], 'wb') as write_out_file: pdfFM.write(write_out_file) # close all the input files. for file in opened_file: file.close()