python学习记录

用python快速批量把word转换为pdf

  1. 需要用到的模块为pywin32 以及python3

下载传送门win32 点我下载

目录解构详情,word文件放在脚本文件同级即可

 完成转换

 

代码整体

from win32com.client import constants,gencache
import os #目录的操作
def createpdf(wordPath,pdfPath):
    word=gencache.EnsureDispatch('Word.Application')
    doc=word.Documents.Open(wordPath,ReadOnly=1)
    #转换方法
    doc.ExportAsFixedFormat(pdfPath,constants.wdExportFormatPDF)
    word.Quit()

#多个文件的转换
print(os.listdir('C:\\Users\\Administrator\\Desktop\\testpdf')) #当前文件夹下的所有文件
wordfiles=[]
for file in os.listdir('C:\\Users\\Administrator\\Desktop\\testpdf'):
    if file.endswith(('.doc','.docx')): #通过后缀找出所有的workd文件
        wordfiles.append(file)
print(wordfiles)

#文件路径和输出路径看你的情况来,发现py获取的当前路径有点问题所以只能绝对路径

for file in wordfiles:
    #获取文件路径
    filepath='C:\\Users\\Administrator\\Desktop\\testpdf\\'+file   #文件的路径
    putpath = 'C:\\Users\\Administrator\\Desktop\\testpdf\\hh\\'+file #输出文件的路径
    print(filepath)
    index=putpath.rindex('.')
    #通过截取获取pdfpath
    pdfpath=putpath[:index]+'.pdf'
    print(pdfpath)
    createpdf(filepath,pdfpath)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值