Search code examples
pythonpypdf

Merging all pdf files in a folder into one pdf with pypdf2


I want to merge all the PDFs in a directory with PyPDF2.

I tried the code from pypdf Merging multiple pdf files into one pdf

from PyPDF2 import PdfFileMerger, PdfFileReader

merger = PdfFileMerger()

for filename in os.listdir():
    merger.append(PdfFileReader(file(filename, 'rb')))

merger.write('Result.pdf')

I got an error!

NameError: name 'file' is not defined

Solution

  • Use a with block

    for filename in os.listdir():
        with open(filename, 'rb') as source:
            tmp = PdfFileReader(source)
            merger.append(tmp)