4

I have watched a video to learn how to merge PDF files into one PDF file. I tried to modify a little in the code so as to deal with a folder which has the PDF files The main folder (Spyder) has the Demo.py and this is the code

import os
from PyPDF2 import PdfFileMerger

source_dir = os.getcwd() + './PDF Files'
merger = PdfFileMerger()

for item in os.listdir(source_dir):
    if item.endswith('pdf'):
        merger.append(item)

merger.write('.PDF Files/Output/Complete.pdf')       
merger.close()

I have a subfolder named PDF Files into the main folder Spyder and in this subfolder I put the PDF files and inside the subfolder PDF Files I created a folder named Output. I got error file not found as for the 1.pdf although when printing the item inside the loop, I got the PDF names.

The Traceback of error

Traceback (most recent call last):
  File "demo.py", line 9, in <module>
    merger.append(item)
  File "C:\Users\Future\AppData\Local\Programs\Python\Python36\lib\site-packages\PyPDF2\merger.py", line 203, in append
    self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)
  File "C:\Users\Future\AppData\Local\Programs\Python\Python36\lib\site-packages\PyPDF2\merger.py", line 114, in merge
    fileobj = file(fileobj, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '1.pdf'
1
  • Please add the full backtrace from the error to your question. Commented Oct 25, 2020 at 5:40

2 Answers 2

7

I could solve it like that

import os
from PyPDF2 import PdfFileMerger

source_dir = './PDF Files/'
merger = PdfFileMerger()

for item in os.listdir(source_dir):
    if item.endswith('pdf'):
        #print(item)
        merger.append(source_dir + item)

merger.write(source_dir + 'Output/Complete.pdf')       
merger.close()
Sign up to request clarification or add additional context in comments.

Comments

3

Shorter, faster stronger!

import glob
from PyPDF2 import PdfMerger

merger = PdfMerger()

for file in glob.glob('PDF_Folder/*.pdf'):
    merger.append(file)

merger.write('Complete.pdf')       
merger.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.