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

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

我正在尝试将我的大学 PDF 合并为一个,因为他们认为按子章节上传所有内容是个好主意..

您可以在下面找到我合并 PDF 的小程序。

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()

错误输出为:

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'

我是运行python3.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

PyPDF2 版本为 1.26.0。

我试过的:

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 


我没试过的:

Taking a break

如果有使用 python 合并 PDF 的更好(有效 ;))方法,请告诉我!

os.listdir() 函数将 return 相对于您列出的目录的名称。

您需要重建打开这些文件的绝对路径。

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