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

Python批量转换.doc为PDF时中断及文件找不到问题求助

问题:Python批量转换.doc到PDF时中途暂停/文件找不到错误

我用Python批量将.doc文件转换为PDF,遇到的问题是5个文件里仅能成功转换3个程序就暂停,偶尔还会出现以下错误:

转换23KB.doc时发生错误: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'Sorry, we couldn’t find your file. Is it possible it was moved, renamed or deleted?\r (D:...//PrintToPdfPowerShell/23KB.doc)', 'wdmain11.chm', 24654, -2146823114), None)

怀疑是转换后后台文档未正常关闭导致该问题,求解决。

待转换文件列表

05/26/2023  05:55 AM             9,281 11KB.docx
05/26/2023  05:55 AM            28,672 12KB.doc
05/26/2023  05:55 AM            36,352 15KB.doc
05/26/2023  05:56 AM           174,592 170KB.doc
05/26/2023  05:55 AM            36,352 23KB.doc

所用代码

import os
import win32com.client

items = os.listdir(r'D:/PrintToPdfPowerShell/')
for file in items:
    if file.endswith('.doc') and not file.startswith('~$'):
        print(file)
        word_app = win32com.client.Dispatch("Word.Application")
        word_app.Visible = False
        try:
            doc = word_app.Documents.Open(r'D:/PrintToPdfPowerShell/' + file, ReadOnly=True, NoEncodingDialog=True)
            doc.SaveAs(r'D:/PrintToPdfPowerShell/' + os.path.splitext(file)[0] + '.pdf', FileFormat=17)
            doc.Close()
        except Exception as e:
            print(f"Error occurred while converting {file}: {str(e)}")
word_app.Quit()

问题原因及修复方案

核心问题

循环内每次创建新的Word实例,且异常场景下未确保文档关闭、实例退出,导致Word进程残留,占用资源甚至锁定文件,引发后续转换失败;同时手动拼接路径存在斜杠格式隐患。

修复后的代码

import os
import win32com.client
from win32com.client import constants

# 仅初始化一次Word实例
word_app = win32com.client.Dispatch("Word.Application")
word_app.Visible = False
# 禁用所有弹窗提示,避免阻塞程序
word_app.DisplayAlerts = constants.wdAlertsNone

folder_path = r'D:/PrintToPdfPowerShell/'
items = os.listdir(folder_path)

for file in items:
    if file.endswith('.doc') and not file.startswith('~$'):
        print(f"正在转换: {file}")
        # 用os.path.join规范路径拼接
        doc_path = os.path.join(folder_path, file)
        pdf_path = os.path.join(folder_path, os.path.splitext(file)[0] + '.pdf')
        doc = None
        try:
            doc = word_app.Documents.Open(doc_path, ReadOnly=True, NoEncodingDialog=True)
            # 用常量替代魔法数字,可读性更强
            doc.SaveAs(pdf_path, FileFormat=constants.wdFormatPDF)
        except Exception as e:
            print(f"转换{file}失败: {str(e)}")
        finally:
            # 无论成功失败,确保文档关闭
            if doc is not None:
                doc.Close(constants.wdDoNotSaveChanges)

# 退出Word实例并释放COM对象,避免残留进程
word_app.Quit()
del word_app

关键优化点

  • 仅创建一次Word实例,减少进程开销与资源占用
  • 使用os.path.join拼接路径,避免手动拼接的格式错误
  • 添加finally块,强制确保文档关闭,避免资源泄漏
  • 禁用Word弹窗提示,防止因弹窗阻塞程序执行
  • 最后显式删除COM对象,彻底清理后台进程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 00:48:36