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

解压合并PDF后删除原文件触发WinError 32权限错误求解决

问题:解压合并PDF后删除文件出现PermissionError错误

我正在开发一个程序,用于解压包含PDF文件的压缩包,将其中的PDF合并为一个文件,最后删除除生成文件外的所有文件。但执行时出现错误:PermissionError:[WinError 32] The process does not have access to the file because it is being used by another process。

以下是我的代码:

import sys, os

sys.path.append("C:\Users\kovac\AppData\Local\Programs\Python\Python311\Lib\site-packages")

import re, glob, zipfile
from os.path import isfile, join
from PyPDF2 import PdfFileMerger, PdfFileReader
from os import listdir, chdir, getcwd, remove

onlyfiles = []
onlyzip = []

# dir in the root
os.chdir("asdfghjkl")

# get all the zip files
for file in glob.glob("*.zip"):
    onlyzip += [file]

# unzip all the zip files
for x in onlyzip:
    with zipfile.ZipFile(x, 'r') as zip_ref:
        zip_ref.extractall()
        zip_ref.close()

# get all the PDF
for file in glob.glob("*.pdf"):
    onlyfiles += [file]

merger = PdfFileMerger()

# print for better view of whats happening
print(f"merging {len(onlyfiles)} files from {len(onlyzip)} zip ({onlyzip}):")
for x in onlyfiles:
    print(f"- {x}")

# merge all th files into a new one 'PDF_MERGED.pdf'
for x in range(0, len(onlyfiles)):
    merger.append(PdfFileReader(open(onlyfiles[x], 'rb')))
merger.write(f"PDF_MERGED.pdf")
merger.close() # Here i thought that could solve the problem but it didn't

# delete all the zip files     it works
for file in onlyzip:
    os.remove(file)

# delete all the pdf files form the list [onlyfiles], it excludes the 'PDF_merged.pdf' file
for file in onlyfiles:
    os.remove(file) # here causes trouble


print("Finished!")

我原本以为zipfile.close()和merger.close()能解决问题,这确实解决了压缩文件的删除问题,但PDF文件的删除仍报错。请问有什么解决思路?


解决思路

  • 核心原因:合并PDF时,你用open(onlyfiles[x], 'rb')打开文件但未显式关闭,这些文件句柄会被Python延迟回收,导致删除时文件仍被占用。

  • 具体修复方案

    1. 用with语句管理PDF文件句柄
      修改合并PDF的循环,确保每个打开的文件都被及时关闭:

      # 替换原合并循环
      for pdf_file in onlyfiles:
          with open(pdf_file, 'rb') as f:
              merger.append(PdfFileReader(f))
      

      with语句会在代码块结束后自动关闭文件,彻底释放资源。

    2. 用with语句管理PdfFileMerger
      进一步优化,将merger的创建也放入with块,无需手动调用close():

      # 替换原merger创建及合并代码
      with PdfFileMerger() as merger:
          print(f"merging {len(onlyfiles)} files from {len(onlyzip)} zip ({onlyzip}):")
          for pdf_file in onlyfiles:
              print(f"- {pdf_file}")
              with open(pdf_file, 'rb') as f:
                  merger.append(PdfFileReader(f))
          merger.write("PDF_MERGED.pdf")
      
    3. 额外优化建议

      • 移除sys.path.append行,Python默认会搜索site-packages目录,无需手动添加。
      • 简化文件收集代码,比如用onlyzip = glob.glob("*.zip")替代循环追加,onlyfiles = glob.glob("*.pdf")同理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:30:50