Concatenate multiple PDFs using python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Concatenate multiple PDFs using python (/thread-25416.html) |
Concatenate multiple PDFs using python - gmehta1996 - Mar-29-2020 I wrote a code to merge pdf files together Following is my code: def merge_pdf(pdf_path,output_pdf): ## Create Logger logging.basicConfig(filename='LogFile.log',format='%(asctime)s %(message)s',filemode='a') logger=logging.getLogger() logger.setLevel(logging.DEBUG) try: os.chdir(pdf_path) except: logger.error(f"{pdf_path} does not exist") return f"{pdf_path} does not exist" ### Get PDF list from the folder pdfmerge=[] for pdf_file in os.listdir('.'): if pdf_file.endswith('.pdf'): pdfmerge.append(pdf_file) pdfWriter = PyPDF2.PdfFileWriter() ### loop through all PDFs for pdf_file in pdfmerge: pdfFileObj=open(pdf_file,'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) ## Open pages for pdf and add them for pageNum in range(pdfReader.numPages): pageObj=pdfReader.getPage(pageNum) pdfWriter.addPage(pageObj) try: ### Save PDF pdfOutput=open(output_pdf+'.pdf','wb') pdfWriter.write(pdfOutput) pdfOutput.close() logger.debug(f"Successfully concatenated PDFs") return "Success" except: logger.error(f"File Not Created \n Check '{output_pdf}'") return f"File Not Created \n Check '{output_pdf}'" ## Enter input folder containing PDFs and Output path to Save COncatenated PDF merge_pdf(pdf_path=r'input path\PDFs',output_pdf=r'output path\PDFs\Output')The code is a user input code and is working file but if i put an output pdf which already exists it shows the following error: I need to change the code so that if i put an output path which already exists, it does not show this error instead goes in the except condition. please help
|