使用Python合并PDF文件

3

我一直在尝试调试这段代码,它可以将一个包含多个PDF文件的文件夹合并成一个PDF文件:

import os
from PyPDF2 import PdfFileMerger
loc = "C:\\Users\\anzal\\desktop\\pdf"
x = [a for a in os.listdir(loc) if a.endswith(".pdf")]
print(x)

merger = PdfFileMerger()
for pdf in x:
    merger.append(open(pdf,'rb'))
with open("result.pdf", "wb") as fout:
    merger.write(fout)

但它无法识别pdf文件 - 我收到以下错误:
['A1098e.pdf', 'J1098e.pdf']
Traceback (most recent call last):
File "combopdf.py", line 14, in <module>
merger.append(open(pdf,'rb'))
FileNotFoundError: [Errno 2] No such file or directory: 'A1098e.pdf'

有没有解决这个问题的想法?谢谢。
1个回答

3

使用绝对路径:

loc = "C:\\Users\\anzal\\desktop\\pdf"
x = [loc+"\\"+a for a in os.listdir(loc) if a.endswith(".pdf")]
     ^^^^^^^^
     add this

现在脚本正在查找.pdf文件的路径是从脚本运行的目录开始的,我相当确定那不是C:/Users/anzal/desktop/pdf


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接