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

合并带空白页的PDF文件Python脚本运行异常求助

问题分析与修复方案

原脚本无法运行的核心问题是文件路径处理错误,以及缺少必要的资源释放逻辑,以下是修复后的完整代码:

# 若提示"no module PyPDF2",请执行命令:pip install PyPDF2
import os
from os import listdir
from os.path import isfile, join
from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter

# 输入文件夹路径并列出所有PDF文件
path = input("Enter the folder location: ")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and f.lower().endswith('.pdf')]

print('\nList of PDF Files:\n')
for file in pdffiles:
    print(file)

def add_blank_to_end(pdf_names: list, folder_path: str) -> list:
    modified_files = []
    for filename in pdf_names:
        full_path = join(folder_path, filename)
        # 使用with语句自动管理文件资源
        with open(full_path, 'rb') as pdf_in:
            pdf_reader = PdfFileReader(pdf_in)
            pdf_writer = PdfFileWriter()
            
            # 添加原文件所有页面
            for page_num in range(pdf_reader.getNumPages()):
                pdf_writer.addPage(pdf_reader.getPage(page_num))
            
            # 添加空白页(最后一个文件可选择不加,若不需要可添加判断)
            pdf_writer.addBlankPage()
            
            # 生成带空白页的文件,保存在原文件夹下,前缀加"blank_"
            new_filename = f"blank_{filename}"
            new_full_path = join(folder_path, new_filename)
            with open(new_full_path, 'wb') as output_stream:
                pdf_writer.write(output_stream)
            
            modified_files.append(new_full_path)
    return modified_files

def merge_pdfs(pdf_paths: list, output_path: str):
    merger = PdfFileMerger()
    for pdf_path in pdf_paths:
        merger.append(pdf_path)
    # 将合并后的文件保存在原文件夹下
    merger.write(join(path, output_path))
    merger.close()

# 执行流程
with_blank_pages = add_blank_to_end(pdffiles, path)
merge_pdfs(with_blank_pages, "merged_bills.pdf")

# 可选:清理临时生成的带空白页的文件
# for temp_file in with_blank_pages:
#     os.remove(temp_file)

关键修改点说明

  • 完整路径处理:所有文件操作都使用join(folder_path, filename)拼接完整路径,避免因当前工作目录不同导致的文件找不到问题
  • 资源自动释放:用with语句打开文件,无需手动调用close(),防止文件句柄泄漏
  • 更严谨的PDF判断:改用f.lower().endswith('.pdf'),避免遗漏大写后缀的PDF文件
  • 临时文件管理:带空白页的临时文件保存在原文件夹下,前缀标识,方便后续清理(可选)
  • 合并文件路径:合并后的文件直接输出到输入文件夹,更符合使用习惯

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:01:12