我正试图把我的大学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'我正在运行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 darwinPyPDF2版本为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的方法,请告诉我!
发布于 2020-12-05 21:36:28
os.listdir()函数将返回相对于您要列出的目录的名称。
您需要重新构造打开这些文件的绝对路径。
for file in pdf_files:
absfile = os.path.join(path, file)
print(absfile)
output.append(absfile)https://stackoverflow.com/questions/65162124
复制相似问题