温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中将docx与doc文件进行转换

发布时间:2021-03-12 17:09:14 来源:亿速云 阅读:503 作者:Leah 栏目:开发技术

怎么在python中将docx与doc文件进行转换?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

from win32com import client
#转换doc为docx
def doc2docx(fn):
  word = client.Dispatch("Word.Application") # 打开word应用程序
  #for file in files:
  doc = word.Documents.Open(fn) #打开word文件
  doc.SaveAs("{}x".format(fn), 12)#另存为后缀为".docx"的文件,其中参数12或16指docx文件
  doc.Close() #关闭原来word文件
  word.Quit()
#转换docx为doc
def docx2doc(fn):
  word = client.Dispatch("Word.Application") # 打开word应用程序
  #for file in files:
  doc = word.Documents.Open(fn) #打开word文件
  doc.SaveAs("{}".format(fn[:-1]), 0)#另存为后缀为".docx"的文件,其中参数0指doc
  doc.Close() #关闭原来word文件
  word.Quit()
docx2doc(u"d:\\python\\1.docx")

如果想转换为其他格式文件,需要在format文件名内修改,并用如下save as 参数

怎么在python中将docx与doc文件进行转换

如docx转换为pDf,用如下语句:

doc.SaveAs("{}.pdf".format(fn[:-5]), 17)

需要说明的是:

要安装OFFICE,如果是使用金山WPS的,则还不能应用

补充:python批量将文件夹内所有doc转成docx

doc转docx函数

import os
from win32com import client
 
def doc_to_docx(path):
  if os.path.splitext(path)[1] == ".doc":
    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open(path) # 目标路径下的文件
    doc.SaveAs(os.path.splitext(path)[0]+".docx", 16) # 转化后路径下的文件
    doc.Close()
    word.Quit()
 
path = ""#填写文件夹路径
doc_to_docx(path)

获取文件夹下的所有文件的绝对路径

import os 
def find_file(path, ext, file_list=[]):
  dir = os.listdir(path)
  for i in dir:
    i = os.path.join(path, i)
    if os.path.isdir(i):
      find_file(i, ext, file_list)
    else:
      if ext == os.path.splitext(i)[1]:
        file_list.append(i)
  return file_list 
 
dir_path = ""
ext = ".doc"
file_list = find_file(dir_path, ext)

源码

import os
from win32com import client
 
def doc_to_docx(path):
  if os.path.splitext(path)[1] == ".doc":
    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open(path) # 目标路径下的文件
    doc.SaveAs(os.path.splitext(path)[0]+".docx", 16) # 转化后路径下的文件
    doc.Close()
    word.Quit()
 
def find_file(path, ext, file_list=[]):
  dir = os.listdir(path)
  for i in dir:
    i = os.path.join(path, i)
    if os.path.isdir(i):
      find_file(i, ext, file_list)
    else:
      if ext == os.path.splitext(i)[1]:
        file_list.append(i)
  return file_list 
 
dir_path = "C:\Users\python"#批量转换文件夹
ext = ".doc"
file_list = find_file(dir_path, ext)
for file in file_list:
  doc_to_docx(file)

关于怎么在python中将docx与doc文件进行转换问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI