Home > Blockchain >  How to use loops to merge PDF files using Python
How to use loops to merge PDF files using Python

Time:11-01

from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger

merger =PdfFileMerger()

merger.append(PdfFileReader(open("seperated1 PDF file556.pdf", 'rb')))
merger.append(PdfFileReader(open("seperated1 PDF file557.pdf", 'rb')))
merger.append(PdfFileReader(open("seperated1 PDF file558.pdf", 'rb')))
merger.append(PdfFileReader(open("seperated1 PDF file559.pdf", 'rb')))
merger.append(PdfFileReader(open("seperated1 PDF file560.pdf", 'rb')))


merger.write("output01.pdf")

I want to merge all Pdf files but I don't know how to use a loop in this case, so I input one by one like the code above.

How do I make use of a loop here to merge all pdf files?

*I have: "seperated1 PDF file1~660.pdf"

Captured vscode

CodePudding user response:

Did you mean this?

from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger

merger = PdfFileMerger()

for n in range(1,601):
    merger.append(PdfFileReader(open(f"seperated1 PDF file{n}.pdf", 'rb')))

merger.write("output01.pdf")
  • Related