Python3: FileNotFoundError: [Errno 2] No such file or directory: 'FIRST_FILENAME.pdf'

Viewed 2635

I am trying to combine my universities PDFs into one as they thought it would be a good idea to upload everything by sub-chapter..

Below you can find my short program to combine the PDFs.

from PyPDF2 import PdfFileReader, PdfFileMerger
import os

path = input("PDFs-to-merge path >> ")
pdf_files = os.listdir(path)

# fn that merges PDFs 
def merge():
           
    print("merge", pdf_files) # This produces no errors, as I can see the list in terminal
    output = PdfFileMerger()
    
    # DEBUG: Code below causes error: File can't be found
    for file in pdf_files:
        print(file)
        output.append(file)

    output.write("merged.pdf")
 
merge()

The error output is:

Traceback (most recent call last):
  File "merge_pdf.py", line 22, in <module>
    merge()
  File "merge_pdf.py", line 18, in merge
    output.append(file)
  File "/Users/username/Development/Python_3/automation_projects/venv/lib/python3.8/site-packages/PyPDF2/merger.py", line 203, in append
    self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)
  File "/Users/username/Development/Python_3/automation_projects/venv/lib/python3.8/site-packages/PyPDF2/merger.py", line 114, in merge
    fileobj = file(fileobj, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '4.6 Distributed Computing.pdf'

I am running python 3.8.6:

Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) 
[Clang 6.0 (clang-600.0.57)] on darwin

The PyPDF2 version is 1.26.0.

What I have tried:

1. Moved script to PDF directory
2. Used os.path.isfile(path) to see if the file exists but I get output: False
2.1 Create a function to rename pdf files and remove whitespace (but then I get same error)

edit:
2.2. I have manually removed the whitespace for a few files and then 2. outputs True and merges 


What I haven't tried:

Taking a break

If there is a better (functioning ;)) way to combine PDFs using python let me know!

1 Answers

The os.listdir() function will return names relative to the directory you're listing then.

You need to reconstruct the absolute path to open those files.

for file in pdf_files:
    absfile = os.path.join(path, file)
    print(absfile)
    output.append(absfile)
Related