Skip to content
Advertisement

Why does this Traceback error come up in Python?

I am writing something that merges a PDF (in a Supplement folder) with many PDFs (in an Input folder) then saves them into an Output folder. This seems to work once taking the first PDF in the Input folder, merging it with the PDF in the Supplement folder, and saving it into the Output folder without issue. But then gives me a Traceback error and does not continue.

Seems like some issue with the for loop but I cannot seem to figure out why.

import os
from PyPDF2 import PdfFileMerger

#Get the file name of the Supplement
sup_path = 'C:/Users/rr176817/Desktop/New folder/Macro/Supplement Merger/Supplement/'
sup_file_name = os.listdir(sup_path)[0]

#Get list of PDFs in Input
input_path = 'C:/Users/rr176817/Desktop/New folder/Macro/Supplement Merger/Input/'
input_file_names = os.listdir(input_path)

#Put Supplement on Inputs and save to Output
merger = PdfFileMerger()
output_path = 'C:/Users/rr176817/Desktop/New folder/Macro/Supplement Merger/Output/'

for file in input_file_names:
    merger.append(sup_path+sup_file_name)
    merger.append(input_path+file)
    merger.write(output_path+file)
    merger.close()

The error I am getting is below:

Traceback (most recent call last):
  File "C:Usersrr176817PycharmProjectsSupMergermain.py", line 17, in <module>
    merger.append(sup_path+sup_file_name)
  File "C:Usersrr176817PycharmProjectsSupMergervenvlibsite-packagesPyPDF2merger.py", line 203, in append
    self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)
  File "C:Usersrr176817PycharmProjectsSupMergervenvlibsite-packagesPyPDF2merger.py", line 175, in merge
    self._associate_bookmarks_to_pages(srcpages)
  File "C:Usersrr176817PycharmProjectsSupMergervenvlibsite-packagesPyPDF2merger.py", line 448, in _associate_bookmarks_to_pages
    bp = b['/Page']
  File "C:Usersrr176817PycharmProjectsSupMergervenvlibsite-packagesPyPDF2generic.py", line 516, in __getitem__
    return dict.__getitem__(self, key).getObject()
KeyError: '/Page'

Edit: To be clear, the output should be many PDFs (1 per file in the Input). Each file in the Input gets the Supplement PDF merged with it then saved to Output. I re-read my post and noticed that might not have been clear.

Advertisement

Answer

You need to create a new PdfFileMerger object each time through the loop, to merge the base file with the current file in the loop.

output_path = 'C:/Users/rr176817/Desktop/New folder/Macro/Supplement Merger/Output/'
sup_path = os.path.join(sup_path, sup_file_name)

for file in input_file_names:
    with PdfFileMerger() as merger:
        merger.append(sup_path)
        merger.append(os.path.join(input_path, file))
        merger.write(os.path.join(output_path, file))

os.path.join() should be used rather than string concatenation to combine directories and filenames.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement