How do I use a list or set as keys in file renaming

Question:

Is something like this possible? Id like to use a dictionary or set as the key for my file renamer. I have a lot of key words that id like to filter out of the file names but the only way iv found to do it so far is to search by string such as key720 = "720" this make it functions correctly but creates bloat. I have to have a version of the code at bottom for each keyword I want to remove.

how do I get the list to work as keys in the search?
I tried to take the list and make it a string with:

str1 = ""
keyres = (str1.join(keys))

This was closer but it makes a string of all the entry’s I think and didn’t pick up any keywords.

so iv come to this at the moment.

keys = ["720p", "720", "1080p", "1080"]

for filename in os.listdir(dirName):
    if keys in filename:    
        filepath = os.path.join(dirName, filename)
        newfilepath = os.path.join(dirName, filename.replace(keys,""))
        os.rename(filepath, newfilepath)

Is there a way to maybe go by index and increment it one at a time? would that allow the strings in the list to be used as strings?

What I’m trying to do is take a file name and rename it by removing all occurrences of the key words.

Asked By: JWatson

||

Answers:

How about using Regular Expressions, specifically the sub function?

from re import sub

KEYS = ["720p", "720", "1080p", "1080"]

old_filename = "filename1080p.jpg"
new_filename = sub('|'.join(KEYS),'',old_filename)

print(new_filename)
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.