如何用python批量转换.doc文件为.docx文件

需要用到的库:

pywin32、os

 

实现效果:

把文件夹下的文件1.doc、2.doc、3.doc 转化成1.docx、2.docx、3.docx,保存到output文件夹下。

代码运行前:

 

代码运行后:

 

 

实现代码:

 

# 批量把".doc"文件另存在".docx"文件

import os
from win32com import client
def doc_to_docx(p,filepath, output_path):
print("路径:{}".format(filepath))
if not os.path.isabs(filepath):
print(f"不是绝对路径")
return
if not os.path.exists(filepath):
print("文件不存在")
return
if os.path.splitext(filepath)[1] != ".doc":
print("文件类型不对")
return
app = client.Dispatch('kwps.Application')
app.DisplayAlerts = False
document = app.Documents.Open(filepath)
document.SaveAs(output_path + "\\" + os.path.splitext(p)[0] + ".docx", 12)
document.Close()
app.Quit()


if __name__ == '__main__':
#需要转换的批量.doc文件所在的文件夹
input_dir = r'C:\Users\Lenovo\Desktop\test'
#转换后保存到指定文件夹
output_path = r'C:\Users\Lenovo\Desktop\test\output'
filenamelist = []
for f in os.listdir(input_dir):
filenamelist.append(f)
print (filenamelist)
for p in filenamelist:
filepath = os.path.join(input_dir,p)
doc_to_docx(p,filepath,output_path)



 

posted @   testblok  阅读(181)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示