找回密码
 立即注册
搜索
热搜: Excel discuz
查看: 1810|回复: 3

用docx2pdf库,批量将Word转换为PDF!

[复制链接]

482

主题

7万

元宝

75万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
750853
发表于 2021-6-17 19:52:19 | 显示全部楼层 |阅读模式
  1. from docx2pdf import convert
  2. import glob
  3. [convert(file,"{}.pdf".format(file.split('.')[0])) for file in glob.glob("*.docx")]
复制代码



回复

使用道具 举报

482

主题

7万

元宝

75万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
750853
 楼主| 发表于 2021-6-17 19:53:00 | 显示全部楼层
没有指定路径,输出到默认文档文件夹,作用是转换当前文件夹内所有Word文档
回复

使用道具 举报

482

主题

7万

元宝

75万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
750853
 楼主| 发表于 2021-6-17 20:11:27 | 显示全部楼层
也可以写成下面这样:
  1. from docx2pdf import convert

  2. import os

  3. wordlist = []                           #创建空列表,存储Word文件名
  4. for file in os.scandir(os.getcwd()):    #这个for循环,是遍历所有docx的文件,加入到列表中
  5.     if file.name.endswith('docx'):
  6.         #print(file.name)
  7.         wordlist.append(file.name)

  8. #print(wordlist)
  9. for i in wordlist:                      #这个for循环,是Word转PDF的步骤,i是文件名
  10.     convert(i, "{}.pdf".format(i.split('.')[0]))

  11.     print(f'文件{i}转换完成')
复制代码
回复

使用道具 举报

482

主题

7万

元宝

75万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
750853
 楼主| 发表于 2021-6-18 13:30:01 | 显示全部楼层
如果py文件和需要转换的文件不在同一个文件夹,就需要修改路径,代码可以写成下面这样,也精简了部分代码:
  1. from docx2pdf import convert
  2. import os
  3. #切换到该目录
  4. os.chdir('f:\\')
  5. for file in os.scandir(os.getcwd()):
  6.     if file.name.endswith('docx'):
  7.         convert(file.name,"{}.pdf".format(file.name.split('.')[0]))
复制代码




回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|五花八门论坛 ( 豫ICP备15031300号-3 )

GMT+8, 2024-5-18 14:09 , Processed in 0.100033 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表