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()
复制代码

 

posted @   夕西行  阅读(430)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示