首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python3: FileNotFoundError:[Errno 2]没有这样的文件或目录:“FIRST_FILENAME.pdf”

Python3: FileNotFoundError:[Errno 2]没有这样的文件或目录:“FIRST_FILENAME.pdf”
EN

Stack Overflow用户
提问于 2020-12-05 21:24:58
回答 1查看 2.8K关注 0票数 2

我正试图把我的大学PDF合并成一个整体,因为他们认为通过分章上传所有东西是个好主意。

下面你可以找到我的短程序组合PDF。

代码语言:javascript
复制
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()

错误输出是:

代码语言:javascript
复制
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'

我正在运行python 3.8.6:

代码语言:javascript
复制
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。

我尝试过的:

代码语言:javascript
复制
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 

我还没试过的:

代码语言:javascript
复制
Taking a break

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-05 21:36:28

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

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

代码语言:javascript
复制
for file in pdf_files:
    absfile = os.path.join(path, file)
    print(absfile)
    output.append(absfile)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65162124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档