import os
from win32com import client
import time
base_dir = r"E:\xx\xxx\xxxx"
for root, dirs, files in os.walk(base_dir):
n = 1
for file in files:
if file.endswith(".doc"):
time.sleep(5)
print(file)
#word = client.Dispatch('Word.Application')
word = client.gencache.EnsureDispatch('Word.Application')
# doc = word.Documents.Open(os.path.join(root, file)) # 目标路径下的文件
doc = word.Documents.Open(os.path.abspath(root + "\\" + file))
# if not os.path.exists(root.replace("xxx", "docx") +"/"):
# os.mkdir(root.replace("xxx", "docx") +"/")
# new_path = root.replace("xxx", "docx") +"/"+ file
# print(new_path)
# doc.SaveAs(os.path.splitext(os.path.join(root, file))[0] + ".docx", 16) # 转化后路径下的文件
doc.SaveAs('E:/xx/xxx/xxxx/docx/'+ file.replace('.doc','.docx'), 16) # 转化后路径下的文件
doc.Close()
word.Quit()
import win32api; ImportError: DLL load failed: 找不到指定的程序
224、225新版本发布的有问题,回退到223版本即可
pip install pywin32==223
pywintypes.com_error: (-2147352573, ‘找不到成员。‘, None, None)
pywintypes.com_error: (-2147023174, ‘RPC 服务器不可用。’, None, None)
raise AttributeError(“%s.%s” % (self.username, attr)) AttributeError: Word
解决方案:
(1) 用绝对路径
(2) base_dir = r"E:\xx\xxx\xxxx" 加了r
(3) os.path.join(root, file) 改为 os.path.abspath(root + “\” + file)
(4) 修改了存储路径(不用os.path.join)
(5) docx 和 doc放在不同文件夹下
(6) 加了 time.sleep(5)
最后不知道哪个起作用了,成功了
python docx.opc.exceptions.PackageNotFoundError:打开文档时找不到包
python docx.opc.exceptions.PackageNotFoundError: Package not found when opening Document
(1)将word = client.Dispatch(‘Word.Application’)改为
word = client.gencache.EnsureDispatch(‘Word.Application’)
未解决
(2)用word(office)打不开,显示文件格式与文件拓展名不匹配(docx实际并不是docx)
发现电脑doc docx默认打开方式为wps,修改默认打开方式为word(office)
enenen,好像还是不行
import os
from win32com import client as wc
word = wc.Dispatch('Word.Application')
#将docx文件保存的路径
docxPath = 'D:\\wyj\\技术文档\\python-doc文件转换成docx文件\\docx'
#doc文件路径
path = "D:\\wyj\\技术文档\\python-doc文件转换成docx文件"
'''
获取doc文件名,创建docx文件路径
'''
def getFileName(path):
filesList = []
for root, dirs, files in os.walk(path):
isExists=os.path.exists(docxPath)
#新建docx文件夹
if not isExists :
os.makedirs(docxPath)
for file in files:
#判断尾缀是不是doc
suffix = file.split('.')[1]
if suffix == 'doc':
filesList.append(file)
print(filesList)
return filesList
'''
将doc文件转换成docx文件
'''
def docToDocx(fileNameList):
try:
for fileName in fileNameList:
print("开始处理 文件名:"+fileName)
doc = word.Documents.Open(path+'\\'+fileName)
#[:-4]的意思是选这个字符串从开始到最后倒数第4位(不含)
docxNamePath = docxPath+'\\'+fileName[:-4]+'.docx'
print('转换完成!'+docxNamePath)
doc.SaveAs(docxNamePath, 12, False, "", True, "", False, False, False, False)
finally:
#一定要记得关闭docx,否则会出现文件占用
doc.Close()
try:
fileNameList = getFileName(path)
docToDocx(fileNameList)
finally:
word.Quit()
参考:https://blog.csdn.net/m0_38072530/article/details/122542818