如何用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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南