python将doc文件转换docx

一:python将doc文件批量转换docx:

# -*- coding:utf-8 -*-
# @Author : yyzhang
import os
import time
from win32com import client

def doc_to_docx(list_dir,save_file):
    word = client.Dispatch("Word.Application")  # 打开word应用程序
    filename_list = [i for i in list_dir if i.split(".")[-1] == "doc"]
    # filename_list=[os.path.join(folder,j) for j in li ]
    # print(filename_list)
    # time.sleep(10)
    try:
        for file in filename_list:
            print("开始转换:",file)
            # print(file)
            # 将doc的文件名换成后缀为docx的文件
            name =  os.path.splitext(file)[0] + '.docx'
            # 将我们的docx与文件保存位置拼接起来,获得绝对路径
            out_name = os.path.join(save_file,name)  #
            print("测试后:",name)
            print("转换后:",out_name)
            # out_file.append(out_name)
            file_path=os.path.join(folder,file)
            doc = word.Documents.Open(file_path)  # 打开word文件
            # doc.SaveAs("{}".format(out_name), 12)  # 另存为后缀为".docx"的文件,其中参数12或16指docx文件
            doc.SaveAs("{}".format(out_name), 12, False, "", True, "", False,
                       False, False,
                       False)  # 转换后的文件,12代表转换后为docx文件
            doc.Close()  # 关闭原来word文件
    except Exception as e:
        print(e)
    word.Quit()

if __name__ == "__main__":
    # 支持文件夹批量导入
    folder = 'C:\\Users\\Desktop\\DOC_docx\\doc-file'
    list_dir=os.listdir(folder)
    # print(list_dir)
    out_dir = 'C:\\Users\\Desktop\\DOC_docx\\doc-file1'
    doc_to_docx(list_dir,out_dir)

二:python将docx文件转换pdf:


import comtypes.client
import win32com
import os
import sys

try:
    from comtypes import client
except ImportError:
    client = None

try:
    from win32com.client import constants, gencache
except ImportError:
    constants = None
    gencache = None


def doc2pdf(docPath, pdfPath):
    docPathTrue = os.path.abspath(docPath)
    # word = gencache.EnsureDispatch('Word.Application')
    word = win32com.client.DispatchEx('Word.Application')
    doc = word.Documents.Open(docPathTrue, ReadOnly=1)
    doc.ExportAsFixedFormat(pdfPath,
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
    word.Quit(constants.wdDoNotSaveChanges)
doc2pdf(r"C:\Users\Desktop\DOC_docx\new_docx\语音专线协议.docx",r"C:\Users\Desktop\DOC_docx\语音专线协议.pdf")

  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空弹壳

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值