使用Python COM转换文件时出错
我有一个非常简单的程序,它使用Python的 comtypes
模块来把 .doc
文件转换成 .docx
文件:
代码如下:
import sys
import os
import comtypes.client
wdFormatDOCX = 16
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open("XYZ.doc")
doc.SaveAs("XYZ.docx", FileFormat=wdFormatDOCX)
doc.Close()
word.Quit()
输入文件和程序在同一个文件夹里,但它总是报错:
Traceback (most recent call last):
File "F:\py\newProj\parse.py", line 8, in <module>
doc = word.Documents.Open("XYZ.doc")
COMError: (-2146823114, None, (u'Sorry, we couldn\u2019t find your file. Is it
possible it was moved, renamed or deleted?\r (C:\\Windows\\system32\\XYZ.doc)',
u'Microsoft Word', u'wdmain11.chm', 24654, None))
我不知道为什么它会在系统目录里找文件,明明我已经给了相对路径。
即使我给了绝对路径,错误依然存在。
那么这里的问题是什么呢?
2 个回答
0
你可以试试这个方法,可能你会觉得这个解决办法有点傻,但实际上它真的有效,一切都很完美。
in_file = str(os.path.abspath("XYZ.docx").replace("c","C") # if the file path in c
doc = word.Documents.Open(in_file)
其实这有点傻,问题出在小写的c上。在我的情况下,问题就是因为小写的c。我把它换成大写的C后就好了(我指的是路径中的小写c,不是说小写c本身)。
1
这个路径需要进行转义。你在当前的环境中启动Python,或者是在系统的上下文中启动。你可以通过打开终端,然后输入以下命令来检查这一点:
import os
print(os.path)
为此,我使用了:
fulldocpath = os.getcwd() + "\\" + doc_file_name os.path.abspath(fulldocpath).replace('\\','\\\\\\\\')
doc = word.Documents.Add(osdocpath)