可先百度查阅os库
import os
import comtypes.client
def get_path_word():
pathpath = input("请输入需要转化Word的路径")
os.chdir(pathpath) #更改工作目录
path = os.getcwd()
pathpdf = input("请输入需要保存的路径 绝对路径")
filename_list = os.listdir(path) # 获取文件名的列表
wordname_list = [filename for filename in filename_list
if filename.endswith((".doc",".docx"))]
for wordname in wordname_list:
pdfname = os.path.splitext(wordname)[0]+".pdf"
#如果当前文件PDF版本存在则不转换
if pdfname in filename_list:
continue
wordpath = os.path.join(path,wordname)#Word所在路径
pdfpath = os.path.join(pathpdf,pdfname) #pdf保存路径
#返回路径给convert_word_to_pdf
yield wordpath,pdfpath
def get_path_ppt():
pathpath = input("请输入需要转化的PPT的绝对路径")
os.chdir(pathpath)#更改工作目录
path = os.getcwd()#将工作目录给path
pathpdf = input("请输入PDF保存的绝对路径")
filename_list = os.listdir(path) #获取文件名路径
pptname_list = [filename for filename in filename_list if filename.endswith((".pptx",".ppt"))]
for pptname in pptname_list:
pdfname = os.path.splitext(pptname)[0]+".pdf"
if pdfname in pptname_list:
continue
pptpath = os.path.join(path,pptname)
pdfpath = os.path.join(pathpdf,pdfname)
yield pdfpath,pptpath
def convert_word_to_pdf():
word = comtypes.client.CreateObject("Word.Application")
word.Visible = 0
for wordpath,pdfpath in get_path_word():
newpdf = word.Documents.Open(wordpath)
newpdf.SaveAs(pdfpath,FileFormat=17)
newpdf.Close()
def convert_ppt_to_pdf():
powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
powerpoint.Visible = 1
for pdfpath,pptpath in get_path_ppt():
newpdf = powerpoint.Presentations.Open(pptpath)
newpdf.SaveAs(pdfpath,32)
newpdf.Close()
powerpoint.Quit()
if __name__ == '__main__':
num = input("1转换Word2转换PPT 大于2的 WordPPT都转换")
if num == 1 :
convert_word_to_pdf()
elif num == 2:
convert_ppt_to_pdf()
else:
convert_word_to_pdf()
convert_ppt_to_pdf()
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200117141836287.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3RodHR0,size_16,color_FFFFFF,t_70)