使用pypdf合并PDF无输出文件:原因排查与修复方法
问题原因与修复方案
问题原因
你的代码存在两个关键问题:
- 核心逻辑未被触发:你把调用
pdf_combiner函数的try-except块写在了函数内部,脚本运行时仅完成了函数定义,从未执行合并PDF的核心逻辑,自然不会生成文件。 - 错误的递归调用:函数内部的
pdf_combiner(files)属于无终止条件的递归调用,即使触发也会引发报错,但这里因为函数从未被外部调用,所以这个问题没暴露出来。
修复后的代码
from pypdf import PdfWriter import sys new_envelope = sys.argv[1] files = sys.argv[2:] def pdf_combiner(file_list): merger = PdfWriter() for pdf in file_list: merger.append(pdf) with open(new_envelope, "wb") as envelope: merger.write(envelope) merger.close() # 将try-except块移到函数外部,作为全局代码触发核心逻辑 try: pdf_combiner(files) except Exception as err: print(f'Error: {err}') print('''Please try again. Input format should be new pdf envelope name followed by PDF files to be added to envelope. Note: All input PDF files must be in the current working directory. Example command: python3 pdf_envelope.py avengers.pdf thor.pdf iron_man.pdf hulk.pdf ''')
额外说明
如果修复后仍未在预期位置找到生成的文件,可检查以下点:
- 执行命令时的当前工作目录:
new_envelope使用相对路径时,文件会生成在你执行python3命令的目录下,而非脚本所在目录。 - 若要强制在当前工作目录生成文件,可添加路径处理逻辑:
import os # 将新文件路径转为当前工作目录的绝对路径 new_envelope = os.path.join(os.getcwd(), sys.argv[1])
内容的提问来源于stack exchange,提问作者Nathan Pena
相关产品推荐
相关产品推荐

