Python-删除以编程方式创建的word和pdf文件
我有一个使用mailmerge从excel文件生成word文档的代码,然后将word文档转换为PDF,然后再从PDF转换为PNG。我正在寻找一种方法来删除word文档后,创建PDF和删除PDF后,创建PNG文件 以下是我正在使用的代码:Python-删除以编程方式创建的word和pdf文件,python,pdf,Python,Pdf,我有一个使用mailmerge从excel文件生成word文档的代码,然后将word文档转换为PDF,然后再从PDF转换为PNG。我正在寻找一种方法来删除word文档后,创建PDF和删除PDF后,创建PNG文件 以下是我正在使用的代码: #Code for the conversion from docx to pdf wdFormatPDF = 17 basepath="C:/Users/.../images" os.chdir
#Code for the conversion from docx to pdf
wdFormatPDF = 17
basepath="C:/Users/.../images"
os.chdir(base_path)
with os.scandir(base_path) as entries:
for entry in entries:
if entry.is_file() and (entry.name[-4:]=="docx"):
in_file=base_path+entry.name
out_file=base_path+entry.name[:-4]+"pdf"
word = win32com.client.DispatchEx('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
print("Document "+out_file+" created !!!")
#word.Quit()
word.Quit()
#Code for the conversion from pdf to png
basepath="C:/Users/.../images"
os.chdir(basepath)
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_file():
if entry.name[-3:]=="pdf":
input_filename=basepath + entry.name
images=convert_from_path(input_filename)
for i, image in enumerate(images):
fname=entry.name[:-4]+".PNG"
image.save(fname,"PNG")
print("Document "+fname+" created !!!\n")
您应该将文件链接保存在一个变量中,然后在不再需要它们后将其删除:
import os
os.remove("/link/to/the/file.pdf")
或者,如果您确定目录中没有其他pdf/docx文件:
import os
for filename in os.listdir(directory):
if filename.endswith(".pdf") or filename.endswith(".docx"):
os.remove(filename)
您可以使用os.remove()
删除任何文件。因此,创建完文档后,只需循环源文件并使用此函数逐个删除它们。