如何解决Python-删除以编程方式创建的Word和pdf文件
我有一个代码,可以使用mailmerge从excel文件生成Word文档,然后再将Word文档转换为PDF,然后从PDF转换为PNG。我正在寻找一种在创建PDF之后删除Word文档并在创建PNG文件之后删除PDF的方法。
下面是我正在使用的代码:
#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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。