我只是想用python合并一些PDF文件,更具体的说是PyPDF2.很简单,但由于某些原因,我得到了一个错误,这根本不理解。
在搜索解决方案时,我发现,其他人也有这个问题。但是,没有找到令我满意的解决方案。
我的合并文件的代码。
from PyPDF2 import PdfFileMerger
def merge(self, work_files, destination_file):
pdf_merger = PdfFileMerger()
for pdf in work_files:
pdf_merger.append(pdf)
#also tried the following with the same results:
#with open(pdf, 'wb') as fileobj:
#merger.append(fileobj)
with open(destination_file, 'wb') as fileobj:
pdf_merger.write(fileobj)
whereas work_files
是要合并的pdf文件的路径列表。destination_file
是合并后的pdf应该保存的文件。
这产生了以下错误(按照要求提供了完整的堆栈跟踪)。
Traceback (most recent call last):
File "main.py", line 9, in <module>
merger.append(fileobj)
File "/home/user/.local/lib/python3.8/sitepackages/PyPDF2/merger.py",line 203,
in append
self.merge(len(self.pages), fileobj, bookmark, pages,
import_bookmarks)
File "/home/user/.local/lib/python3.8/site-
packages/PyPDF2/merger.py",
line 133, in merge
pdfr = PdfFileReader(fileobj, strict=self.strict)
File "/home/user/.local/lib/python3.8/site-
packages/PyPDF2/pdf.py", line 1084,
in __init__
self.read(stream)
File "/home/user/.local/lib/python3.8/site
packages/PyPDF2/pdf.py", line 1689,
in read
stream.seek(-1, 2)
OSError: [Errno 22] Invalid argument
我尝试了不同的路径输入方式,我尝试了相对路径、绝对路径以及将它们解析为另一个文件,但没有成功。
我使用的是python 3.8,工作在Linux Ubuntu 20.04上。
如果有任何帮助,我将不胜感激。
如果work_files只是一个列表,那就会出现一个错误。路径 就是说你只是路过 字符串 作为append方法的输入,一次一个。根据 PdfFileMerger 文档,你需要将文件对象作为输入传递给append方法。
fileobj - 一个文件对象或一个支持标准读取和寻找方法的对象,类似于一个文件对象。也可以是一个字符串,代表一个PDF文件的路径。
对不起,我忽略了文档的最后一部分,但你是否真的尝试过传递文件对象?也可以尝试用 glob.glob(*.pdf) 方法获取文件名。如果你能发布错误的完整堆栈跟踪,那也会很有帮助。
在尝试了其他方法来合并PDF文件后,我尴尬地意识到,我的测试文件实际上是损坏的文件,甚至无法被系统读取--问题解决了。