A program to use Powerpoint with Python

A program to use Powerpoint with Python, with the pptx module. Python is very useful for a lot of things that can make you save a lot of time. Let’s see how to use it to make a presentation faster and in a more pleasant way with the complete instructions to create a whole presentation just with Python with no need to manage Powerpoint.

Taking data from an external txt file

The txt file is this

Titolo 1

Paragrafo 1.

Titolo 2

Paragrafo 2...

 

The code is this

from pptx import Presentation
import os, glob

prs = Presentation()

def slide(number=0):
    title_slide_layout = prs.slide_layouts[number]
    slide = prs.slides.add_slide(title_slide_layout)
    title = slide.shapes.title
    subtitle = slide.placeholders[1]
    title.text = file.readline()
    file.readline()
    subtitle.text = file.readline()
    file.readline()  # salta la riga vuota


def choose_file():
    # returns the file chosen in the dir
    flist = glob.glob("*.txt") 
    for f in flist:
        print(flist.index(f), f)
    fchoose = int(input("Choose NUMBER: "))
    return flist[fchoose]

if __name__ == "__main__":
    file_chosen = choose_file()
    with open(file_chosen, 'r', encoding="utf-8") as file:
        file_lenght = len(file.readlines())
        file.seek(0)
        slide(0)
        for i in range(int(file_lenght / 4)):
            slide(1)
    file_to_save = file_chosen[:-4] + ".pptx"
    prs.save(file_to_save)
    os.startfile(file_to_save)

When the program runs, you are asked to choose a txt file among the ones in the folder (there is only one in this particular case):

So you insert the number on the left of the title you want

The output is this

And you will see another file in the folder, the pptx file yet created:

The power.py is the python file, the prova.txt is the file with the data and the prova.pptx is the powerpoint generated by the code.

Insert an image in Powerpoint with Python

The post with the code to fit the image (watch the video) is here.


Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.