admin管理员组

文章数量:1593157

因为自己的作业需要把80个word文档转换成pdf格式,找了下网上现成的批量转换工具基本都是收费的,自己又懒得一个一个转,网上找了下发现很多都是python2写的,于是用python3重写了一个程序。

程序功能:遍历当前文件夹下的所以后缀为.docx的文件,将其转换为对应的pdf文件

转化前:

文件1.docx

文件2.docx

转化后:

文件1.pdf

文件2.pdf

import os
from docx2pdf import convert


# 目录地址,将'/'替换成需要转换的目录地址就行
file_path = r'/'

#转换word->pdf
# 查找当前目录下的全部word文件
for dirpath, dirnames, filenames in os.walk(file_path):
    for file in filenames:
        fullpath = os.path.join(dirpath, file)
        print('fullpath:"'+fullpath)
        # convert("input.docx", "output.pdf")
        convert(fullpath, f"{fullpath}.pdf")  # 转换成pdf文件,但文件名是.docx.pdf,需要重新修改文件名

# 修改文件名
for dirpath, dirnames, filenames in os.walk(file_path):
    for fullpath in filenames:
        # print(fullpath)
        if '.pdf' in fullpath:
            fullpath_after = os.path.splitext(fullpath)[0]
            fullpath_after = os.path.splitext(fullpath_after)[0]
            fullpath_after = fullpath_after + '.pdf'
            fullpath_after = os.path.join(dirpath + '\\' + fullpath_after)
            # print('fullpath_after:' + fullpath_after)
            fullpath = os.path.join(dirpath, fullpath)
            # print('fullpath:'+fullpath)
            os.rename(fullpath, fullpath_after)

本文标签: 转换成批量wordPDF