Home > OS >  Merge PDF Files in subfolders raises FileNotFoundError
Merge PDF Files in subfolders raises FileNotFoundError

Time:10-28

In my case, I have a main folder "Documents" and inside the folder there are subfolders. Inside the subfolders, there pdf files that I am seeking to merge into one pdf file for each sub folder Here's my try till now

import os
from PyPDF2 import PdfFileMerger

myDirectory = 'Documents'
mylist = list(map(lambda x: os.path.join(os.path.abspath(myDirectory), x),os.listdir(myDirectory)))

for d in mylist:
    print(d)
    sFolder = os.path.basename(d)

    x = [a for a in os.listdir(d) if a.endswith('.pdf')]
    merger = PdfFileMerger()

    for pdf in x:
        merger.append(open(pdf, 'rb'))

    with open(sFolder   '.pdf', 'wb') as fout:
        merger.write(fout)

When executing the code, I encountered an error like that

Traceback (most recent call last):
  File "demo.py", line 30, in <module>
    merger.append(open(pdf, 'rb'))
FileNotFoundError: [Errno 2] No such file or directory: '2600-002947-374.pdf'

How can I fix such an error? Is the cause of the error the names of the pdf files?

CodePudding user response:

You need to change only this part:

for pdf in x:
    merger.append(open(os.path.join(d, pdf), 'rb'))

The complete code below worked for me.

import os
from PyPDF2 import PdfFileMerger

myDirectory = 'Documents'
mylist = list(map(lambda x: os.path.join(os.path.abspath(myDirectory), x),os.listdir(myDirectory)))

for d in mylist:
    print(d)
    sFolder = os.path.basename(d)

    x = [a for a in os.listdir(d) if a.endswith('.pdf')]
    merger = PdfFileMerger()

    for pdf in x:
        merger.append(open(os.path.join(d, pdf), 'rb'))

    with open(sFolder   '.pdf', 'wb') as fout:
        merger.write(fout)
  • Related