Python实现将文件夹下的所有pdf文件合并成一个pdf文件,并用文件夹名字命名
import os
import PyPDF2def merge_pdfs ( folder_path) : folder_name = os. path. basename( folder_path) pdf_files = [ f for f in os. listdir( folder_path) if f. endswith( '.pdf' ) ] pdf_files. sort( ) pdf_merger = PyPDF2. PdfMerger( ) for pdf_file in pdf_files: file_path = os. path. join( folder_path, pdf_file) pdf_merger. append( file_path) output_path = os. path. join( os. path. dirname( folder_path) , f" { folder_name} .pdf" ) with open ( output_path, 'wb' ) as output_file: pdf_merger. write( output_file) pdf_merger. close( ) print ( f"PDFs merged into ' { output_path} '" )
source_dir = r''
if not os. path. exists( source_dir) : print ( f"文件夹 { source_dir} 不存在" ) exit( )
dir_1= os. listdir( source_dir)
for path1 in dir_1: if not os. path. isfile( source_dir+ f'\ { path1} ' ) : dir_2= os. listdir( source_dir+ f'\ { path1} ' ) for path2 in dir_2: if not os. path. isfile( source_dir+ f'\ { path1} ' + f'\ { path2} ' ) : deal_dir= source_dir+ f'\ { path1} ' + f'\ { path2} ' folder_path = deal_dirmerge_pdfs( folder_path)