python word.documents.open报错_Python处理word到PDF,python,转,pdf
当实现word文档转换未pdf格式时,单个文档单次执行没有任何问题,但是当将一个文件夹下的目录进行批量转换时,遇到报错:
Traceback (most recent call last):
File "e:/workspace/python/wordtopdf.py", line 33, in
createpdf(filepath,pdfpath)
File "e:/workspace/python/wordtopdf.py", line 9, in createpdf
doc=word.Documents.Open(wordPath,ReadOnly=1)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\__init__.py", line 474, in __getattr__
return self._ApplyTypes_(*args)
File "C:\Users\user1\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\__init__.py", line 467, in _ApplyTypes_
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
pywintypes.com_error: (-2147023174, 'RPC 服务器不可用。', None, None)
解决方法:
from time import sleep
sleep(2) #在循环中加上这条代码
原因:由于循环,当文件读写速度较快的时候,上一个word未关闭,下一个就打开,导致出现以上问题。
代码:
#pywin32,pip install pywin32
from win32com.client import constants,gencache
import os
from time import sleep
def createpdf(wordPath,pdfPath):
word=gencache.EnsureDispatch("Word.Application")
doc=word.Documents.Open(wordPath,ReadOnly=1)
#转换方法
doc.ExportAsFixedFormat(pdfPath,constants.wdExportFormatPDF)
word.Quit()
#单个文件转换
# createpdf("E:/workspace/python/info.docx","E:/workspace/python/info.pdf")
#多个文件转换
# print(os.listdir(".")) #当前文件夹下面的所有文件
wordfiles=[]
for file in os.listdir("."):
if file.endswith((".doc",".docx")):
wordfiles.append(file)
print(wordfiles)
for file in wordfiles:
filepath=os.path.abspath(file)
index=filepath.rindex(".")
pdfpath=filepath[:index]+".pdf"
print(filepath)
print(pdfpath)
createpdf(filepath,pdfpath)
sleep(2)
更多推荐


所有评论(0)