Search code examples
pythonpowerpoint

Python: Change file names to the names of people in a list


I have a couple slides, each slide corresponds to a person. I need to name each file (.pptx) after the individual name it references. A lot of the examples I see on mass renaming have the renaming become sequential like:

file1
file2
file3

I need:

bob.pptx
sue.pptx
jack.pptx

I was able to change names using os found on this site https://www.marsja.se/rename-files-in-python-a-guide-with-examples-using-os-rename/:

import os, fnmatch
file_path = 'C:\\Users\\Documents\\Files_To_Rename\\Many_Files\\'
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.pptx')
print(files_to_rename)
new_name = 'Datafile'

for i, file_name in enumerate(files_to_rename):
    new_file_name = new_name + str(i) + '.pptx'
    
    os.rename(file_path + file_name, 
          file_path + new_file_name)

But again, this just names it:

Datafile1
Datafile2
etc

Solution

  • Thank you everyone for your suggestions, I think I found it with a friend's help:

    import os, fnmatch
    import pandas as pd
    file_path = 'C:\\Users\\Documents\\FolderwithFiles\\'
    files_to_rename = fnmatch.filter(os.listdir(file_path), '*.pptx') #looks for any .ppt in path, can make any ext
    
    df = pd.read_excel('Names.xlsx') #make a list of names in an xl, this won't read the header, header should be Names, then list your names)
    
    for i, file_name in zip(df['Names'], files_to_rename): #zip instead of a nest for loop
        new_file_name = i + '.pptx'
        os.rename(file_path + file_name, file_path + new_file_name)
        print(new_file_name)