You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyPDF2执行append操作输出数百张空白页问题求助

问题核心原因

    1. 循环遍历列表逻辑错误:你把cv_select(完整绝对路径)追加到了仅存储coverletter目录下短文件名的pdf_file列表中,循环到cv_select这一项时,执行os.path.join(coverletter_directory, pdf)会拼接出非法路径:Windows下如果第二个参数是绝对路径,os.path.join会直接返回第二个参数,非Windows系统则会生成完全不存在的路径,导致PyPDF2读取不到有效PDF内容,最终生成空白页。
    • 当CV和coverletter在同一文件夹时,拼接后的路径刚好合法,所以不会出现问题
    1. 多余的循环项:你的需求是给每个coverletter的PDF末尾追加CV,仅需要遍历coverletter目录下的PDF即可,不需要把CV文件加入循环列表,否则还会额外生成一个不需要的CV同名输出文件。

修复方案

调整globconvert函数的逻辑即可,修复后的代码如下:

def globconvert():   
    if coverletter_directory and cv_select and output_directory:
        # 只保留coverletter目录下的PDF,不要把CV加进循环列表
        pdf_file = [f for f in os.listdir(coverletter_directory) if f.endswith(".pdf")]
        count = 0
        for pdf in pdf_file:
            srcfile = os.path.join(coverletter_directory, pdf)
            outfile = os.path.join(output_directory, pdf)
            print(f"{srcfile} --> {outfile}")
            combine = PdfFileMerger()
            combine.append(srcfile)
            # cv_select本身是完整路径,直接传入即可不需要拼接
            combine.append(cv_select)
            combine.write(outfile)
            combine.close()
            count +=1
        messagebox.showinfo("PDF Merge", f"Total {count} PDF files created")
    else:
        messagebox.showwarning("PDF Merge", "Please select covers folder, CV and output folder")

附加优化建议

  • 如果使用的是2.0以上版本的PyPDF2,PdfFileMerger已经被标记为废弃,建议替换为PyPDF2.PdfMerger,兼容性和稳定性更好
  • 可以在执行append操作前添加路径有效性校验,避免因为路径错误生成空白文件

内容的提问来源于stack exchange,提问作者PythonPerson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:21:03