'Unable to delete PowerPoint Slides using Python-pptx

I am trying to delete PowerPoint slides containing a specific keywords using Python-pptx. If the keyword is present anywhere in the slide then that slide will be deleted. My code is given below:

from pptx import Presentation

String = 'Macro'

ppt = Presentation('D:\\Shaon\\pptss\\Regional.pptx')

for slide in ppt.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            shape.text = String
            slide.delete(slide)

ppt.save('BODd.pptx')

After execution I am getting a memory error. No clue how to resolve this issue. How can I delete ppt slides using some specific keywords?



Solution 1:[1]

You can delete a slide with a specific index value with the following code using the pptx library:

from pptx import Presentation
#  create slides ------
presentation = Presentation('new.pptx') 

xml_slides = presentation.slides._sldIdLst  
slides = list(xml_slides)
xml_slides.remove(slides[index]) 

So to delete the first slide, index would be 0.

Solution 2:[2]

It is possible to delete the whole slides using the following code. So just use this before generating the slides to have a clean and empty PowerPoint file. By changing the index, you can also delete the specific slides.

import os
import pptx.util
from pptx import Presentation

cwd = os.getcwd()
prs = Presentation(cwd + '\\ppt.pptx')
for i in range(len(prs.slides)-1, -1, -1): 
    rId = prs.slides._sldIdLst[i].rId
    prs.part.drop_rel(rId)
    del prs.slides._sldIdLst[i]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ferhat
Solution 2 HMD.F