简体   繁体   中英

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

Use a with block

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM