python:读取文件时出现COMERROR

问题描述 投票:0回答:3

我使用Windows和Jupyter编写python代码,当我使用包comtypes.client时,它不稳定,有时可以工作,有时不行。我正在做的是将 pptx 文件转换为 pdf 文件。这是我的代码:

import comtypes.client

def PPTtoPDF(inputFileName, outputFileName, formatType = 32):
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdf
    deck.Close()
    powerpoint.Quit()

PPTtoPDF('07-20 contact PPT.pptx','./Reports/07-20 contact result',32)

错误是:

COMError: (-2147024894, 'The system cannot find the file specified.', (None, None, None, 0, None))

我不认为这段代码有什么问题,因为它运行了好几次,所以可能是因为计算机环境或其他原因。谁能告诉我如何使这段代码稳定,或者有没有更好的方法可以在 python 中将 PPTX 转换为 PDF?

谢谢大家~

python pdf powerpoint comtypes
3个回答
0
投票

我收到了同样的错误,并且我有一台 64 位 Windows PC。我的解决方案涉及指定文件路径:

# Open the ppt file path. sys.argv[1] is the ppt name.
mypath = os.path.abspath(__file__)
mydir = os.path.dirname(mypath)
file_input = os.path.join(mydir, sys.argv[1])

# create the pdf output file path and call your function 
file_output = os.path.join(mydir, sys.argv[1][:-4] + "pdf")
PPTtoPDF(file_input, file_output)

0
投票

如果有人仍然遇到此错误,我所做的就是像这样手动更改输入和输出路径。

#the double quotes make it a single quote
inputFileName=inputFileName.replace("/","\\") 
outputFileName=outputFileName.replace("/","\\")

0
投票

我也遇到了同样的问题,经过多次尝试和错误,我找到了。

从 comtypes.client.CreateObject() 创建的对象需要文件的绝对路径。

解决方法如下:

from os.path import abspath
import comtypes.client

def PPTtoPDF(inputFileName, outputFileName, formatType = 32):
    inputFileName = abspath(inputFileName) #Transform to Absolute Path
    outputFileName = abspath(outputFileName) #Transform to Absolute Path

    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"

    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdf
    deck.Close()
    powerpoint.Quit()

PPTtoPDF('07-20 contact PPT.pptx','./Reports/07-20 contact result',32)
© www.soinside.com 2019 - 2024. All rights reserved.