示例代码:
import os
from PyPDF2 import PdfFileMerger
folder_path = '/path/to/input/folder'
output_path = '/path/to/output/folder'
for folder_name in os.listdir(folder_path):
if not os.path.isdir(os.path.join(folder_path, folder_name)):
continue
# 初始化PdfFileMerger对象
merger = PdfFileMerger()
for file_name in os.listdir(os.path.join(folder_path, folder_name)):
# 只合并PDF文件
if not file_name.lower().endswith('.pdf'):
continue
# 将PDF文件加入到PdfFileMerger对象中
merger.append(os.path.join(folder_path, folder_name, file_name))
# 如果文件夹内没有PDF文件,则跳过此文件夹
if merger.filestr == b'':
continue
# 保存合并后的PDF文件到输出文件夹中
output_file_path = os.path.join(output_path, folder_name + '.pdf')
merger.write(output_file_path)
上一篇:按文件夹分组以用于删除