为什么这个 Traceback 错误出现在 Python 中?

Why does this Traceback error come up in Python?

我正在写一些东西,将一个 PDF(在 Supplement 文件夹中)与许多 PDF(在一个 Input 文件夹中)合并,然后将它们保存到一个 Output 文件夹中。一旦在 Input 文件夹中获取第一个 PDF,将其与 Supplement 文件夹中的 PDF 合并,然后毫无问题地将其保存到 Output 文件夹中,这似乎就起作用了。但是然后给我一个回溯错误并且没有继续。

for 循环似乎有问题,但我似乎无法弄清楚原因。

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()

我收到的错误如下:

Traceback (most recent call last):
  File "C:\Users\rr176817\PycharmProjects\SupMerger\main.py", line 17, in <module>
    merger.append(sup_path+sup_file_name)
  File "C:\Users\rr176817\PycharmProjects\SupMerger\venv\lib\site-packages\PyPDF2\merger.py", line 203, in append
    self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)
  File "C:\Users\rr176817\PycharmProjects\SupMerger\venv\lib\site-packages\PyPDF2\merger.py", line 175, in merge
    self._associate_bookmarks_to_pages(srcpages)
  File "C:\Users\rr176817\PycharmProjects\SupMerger\venv\lib\site-packages\PyPDF2\merger.py", line 448, in _associate_bookmarks_to_pages
    bp = b['/Page']
  File "C:\Users\rr176817\PycharmProjects\SupMerger\venv\lib\site-packages\PyPDF2\generic.py", line 516, in __getitem__
    return dict.__getitem__(self, key).getObject()
KeyError: '/Page'

编辑: 明确地说,输出应该是许多 PDF(输入中每个文件 1 个)。 Input 中的每个文件都会将 Supplement PDF 与其合并,然后保存到 Output。我重新阅读了我的 post 并注意到可能还不清楚。

每次循环都需要创建一个新的PdfFileMerger对象,将基础文件与循环中的当前文件合并。

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() 而不是字符串连接来组合目录和文件名。