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

Python合并PDF遇损坏与参数错误,如何通过filelist.txt按序合并?

解决按指定顺序合并PDF的问题

第一步:规范filelist.txt的格式

确保文件内每行是一个PDF的有效路径:

  • 若PDF和脚本在同一文件夹,直接写文件名,比如report_01.pdf
  • 子文件夹下的文件写相对路径,比如./pdfs/report_02.pdf
  • Windows系统用斜杠/或双反斜杠\\写绝对路径,比如C:/Users/xxx/Documents/report_03.pdf
  • 每行仅存一个路径,删除多余空格、空行

第二步:修复PyPDF2合并代码

先更新PyPDF2到最新版本,避免旧版本bug:

pip install --upgrade PyPDF2

使用以下代码,完善路径校验和资源释放逻辑:

from PyPDF2 import PdfMerger
import os

# 读取filelist中的路径,过滤空行
with open('filelist.txt', 'r', encoding='utf-8') as f:
    pdf_paths = [line.strip() for line in f if line.strip()]

merger = PdfMerger()

for path in pdf_paths:
    # 提前校验路径有效性
    if not os.path.exists(path):
        print(f"警告:文件不存在,跳过:{path}")
        continue
    try:
        # 用上下文管理器确保文件正确关闭
        with open(path, 'rb') as pdf_file:
            merger.append(pdf_file)
        print(f"已添加:{path}")
    except Exception as e:
        print(f"处理文件出错,跳过:{path},错误:{str(e)}")

# 写入并关闭资源
try:
    with open('merged_result.pdf', 'wb') as output:
        merger.write(output)
    print("合并完成,结果文件:merged_result.pdf")
finally:
    merger.close()

第三步:排查常见异常

  • 路径不存在错误:核对filelist内的文件名、大小写(Linux/macOS区分大小写)、文件夹名称是否完全正确
  • 生成PDF损坏:
    • 单独打开报错的PDF,确认文件本身未损坏
    • 若PDF加密,在append时添加密码参数:merger.append(pdf_file, password="你的密码")
    • 若PyPDF2仍有问题,换用PyMuPDF(fitz)实现,兼容性更好:
import fitz

merged_pdf = fitz.open()

with open('filelist.txt', 'r', encoding='utf-8') as f:
    pdf_paths = [line.strip() for line in f if line.strip()]

for path in pdf_paths:
    if not os.path.exists(path):
        print(f"警告:文件不存在,跳过:{path}")
        continue
    try:
        with fitz.open(path) as pdf:
            merged_pdf.insert_pdf(pdf)
        print(f"已添加:{path}")
    except Exception as e:
        print(f"处理文件出错,跳过:{path},错误:{str(e)}")

merged_pdf.save('merged_result.pdf')
merged_pdf.close()

第四步:验证结果

打开生成的merged_result.pdf,检查页面顺序是否与filelist一致、所有页面是否完整显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:54:51