0

I have several PDF files located in a folder on my Desktop called Highlighted and stored the path of this directory into a variable called filePath.

Given a list of actor names called actorList, I want to merge all the PDFs starting with similar names (e.g., Adam, Sandler) in the filePath directory, separately (please see the image below).

enter image description here

import os
from PyPDF2 import PdfFileMerger

actorList = ['Adam, Sandler', 'Daniel, Craig', 'Jennifer, Aniston']
filePath  = r'C:\Users\Mike\Desktop\Highlighted' + '\\'
fileList  = []

for actorName in actorList:
   for path, currentDirectory, files in os.walk(filePath):
      for fileName in files:
         if fileName.startswith(actorName):
            fileList.append(fileName)

# Append & Merge all PDFs starting with similar names 
merger = PdfFileMerger()
for actorName in actorList:
    for fileName in fileList:
        if actorName not in fileName:
            continue
        merger.append(filePath + fileName)
    merger.write(filePath + actorName + '.pdf')
    merger.close()

I have tried all methods here, but had no luck! Any thoughts please??

GeekyCoder
  • 11
  • 1

1 Answers1

0

The problem was solved after moving the merger inside the outer for loop. I was getting the NoneType error, because the merger was not initialized after each time it was getting closed by merger.close().

# merger = PdfFileMerger()   =====> move the PdfFileMerger() from OUTSIDE
    for actorName in actorList:                                       
        merger = PdfFileMerger() # <===== to INSIDE
        for fileName in fileList:
            if actorName not in fileName:
                continue
            merger.append(filePath + fileName)
        merger.write(filePath + actorName + '.pdf')
        merger.close()
GeekyCoder
  • 11
  • 1