Search code examples
pythonstringlistsubdirectoryos.walk

removing substrings from subdirectory names using values held in list


I have a parent directory that contains a lot of subdirectories. I want to create a script that loops through all of the subdirectories and removes any key words that I have specified in the list variable.

I am not entirely sure how to acheive this.

Currently I have this:

import os
directory = next(os.walk('.'))[1]


stringstoremove = ['string1','string2','string3','string4','string5']


for folders in directory:
    os.rename

And maybe this type of logic to check to see if the string exists within the subdirectory name:

if any(words in inputstring for words in stringstoremove):
    print ("TRUE")
else:
    print ("FALSE")

Trying my best to to deconstruct the task, but I'm going round in circles now

Thanks guys


Solution

  • Startng from your existing code:

    import os
    directory = next(os.walk('.'))[1]
    
    stringstoremove = ['string1','string2','string3','string4','string5']
    
    for folder in directory :
        new_folder = folder
        for r in stringstoremove :
            new_folder = new_folder.replace( r, '')
    
        if folder != new_folder :  # don't rename if it's the same
            os.rename( folder, new_folder )