python批量将docx转为pdf|异步
作者:YXn-python 阅读量:50 发布日期:2024-05-21
import os
import asyncio
from docx2pdf import convert
# pip install docx2pdf
"""
异步 docx文件转pdf 无需等待,不会阻塞转换
"""
# docx文档转pdf
async def docx_to_pdf(docx_path, save_path=None):
if save_path:
pdf_path = os.path.join(os.path.dirname(docx_path), save_path, os.path.basename(docx_path)[:-5] + '.pdf')
else:
pdf_path = os.path.splitext(docx_path)[0] + '.pdf'
await convert(docx_path, pdf_path)
print(f'{docx_path}转换成功!')
async def main(docx_urls):
tasks = []
for url in docx_urls:
task = asyncio.create_task(docx_to_pdf(url, 'pdf'))
tasks.append(task)
await asyncio.gather(*tasks)
def run():
while True:
f_path = str(input('请(拖入/输入)(docx文件/文件夹)地址: '))
if not os.path.exists(f_path):
print('不存在该文件或文件夹,请重新输入!')
continue
if os.path.isfile(f_path):
if os.path.splitext(f_path)[1] != '.docx':
print('不支持的格式,请输入docx文件!')
continue
break
if os.path.isdir(f_path):
if not os.path.isdir(os.path.join(f_path, 'pdf')):
os.mkdir(os.path.join(f_path, 'pdf'))
# 获取文件夹下所有docx文件
files = [os.path.join(f_path, file) for file in os.listdir(f_path) if file.endswith('.docx')]
if len(files) == 0:
print('文件夹下没有docx文件!')
return
loop = asyncio.get_event_loop() # 开启事件循环对象
loop.run_until_complete(main(files)) # 用事件循环对象开启协程异步对象
elif os.path.isfile(f_path):
docx_to_pdf(f_path)
print('转换完成!')
if __name__ == '__main__':
run()
input('按回车退出...')
YXn-python
2024-05-21