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

Python批量重命名PDF脚本报错:仅处理首个文件后提示Document closed

修复PDF重命名脚本的“Document closed”错误

问题根源

核心错误是手动调用pdf_file.close()与with上下文管理器的自动关闭机制冲突:
with fitz.open(...) as pdf_file会在代码块结束时自动关闭PDF文档,手动调用pdf_file.close()会导致文档被提前关闭;当with块结束时再次尝试关闭已关闭的文档,触发RuntimeError: Document closed,导致脚本在处理完首个文件后终止。

修复后的代码

import fitz
from dateutil.parser import parse
import os
from glob import glob

# 指定PDF文件夹路径
pdf_folder = 'E:/PYTHON/dummyData/'

# 遍历文件夹内所有PDF文件(直接获取完整路径)
for file_path in glob(os.path.join(pdf_folder, '*.pdf')):
    file_name = os.path.basename(file_path)
    
    # 用with上下文管理器自动管理PDF文档资源
    with fitz.open(file_path) as pdf_file:
        text = ''
        # 提取所有页面文本
        for page_num in range(pdf_file.page_count):
            page = pdf_file.load_page(page_num)
            text += page.get_text()
        
        # 提取符合长度的日期
        dates = []
        for word in text.split():
            try:
                date = parse(word, fuzzy=True)
                # 筛选长度为10或11的日期字符串(如DD-MM-YYYY或类似格式)
                if len(word) in (10, 11):
                    dates.append(date)
            except (ValueError, OverflowError):
                continue
    
    # 重命名文件(确保在with块外执行,避免文件占用)
    if dates:
        new_name = f"{dates[0].strftime('%d-%m-%y')} {file_name}"
        new_file_path = os.path.join(pdf_folder, new_name)
        # 避免重名覆盖
        if not os.path.exists(new_file_path):
            os.rename(file_path, new_file_path)
            print(f"文件 {file_name} 已重命名为 {new_name}")
        else:
            print(f"文件 {new_name} 已存在,跳过重命名 {file_name}")
    else:
        print(f"未在 {file_name} 中找到日期")

关键修复点

  1. 移除手动的pdf_file.close()调用,完全依赖with上下文管理器自动关闭PDF文档,避免重复关闭引发错误。
  2. 使用glob.glob()直接获取所有PDF文件的完整路径,简化代码逻辑,避免手动拼接路径的冗余操作。
  3. 将重命名操作移至with块外部,确保PDF文档已完全关闭,避免文件占用导致重命名失败。
  4. 添加重名检查,避免因重复日期导致文件被覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:55:42