Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging PDF files with Python

Tags:

python

pdf

I have been trying to debug this code for merging a folder of pdf's into one pdf file:

import os
from PyPDF2 import PdfFileMerger
loc = "C:\\Users\\anzal\\desktop\\pdf"
x = [a for a in os.listdir(loc) if a.endswith(".pdf")]
print(x)

merger = PdfFileMerger()
for pdf in x:
    merger.append(open(pdf,'rb'))
with open("result.pdf", "wb") as fout:
    merger.write(fout)

But it doesn't recognize the pdf files - I get the following error:

['A1098e.pdf', 'J1098e.pdf']
Traceback (most recent call last):
File "combopdf.py", line 14, in <module>
merger.append(open(pdf,'rb'))
FileNotFoundError: [Errno 2] No such file or directory: 'A1098e.pdf'

Any ideas on how to fix this? Thanks.

like image 596
Mike Avatar asked Feb 28 '26 00:02

Mike


1 Answers

Use absolute paths:

loc = "C:\\Users\\anzal\\desktop\\pdf"
x = [loc+"\\"+a for a in os.listdir(loc) if a.endswith(".pdf")]
     ^^^^^^^^
     add this

Right now it's looking for the .pdf files in the directory from which the script is being ran, and I'm pretty sure that's not C:/Users/anzal/desktop/pdf.

like image 166
Nino Filiu Avatar answered Mar 01 '26 17:03

Nino Filiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!