pythondirectorydelete-fileshutil

Python how to delete a directory that contains a specific word


Hey I want to delete folders in Windows which contain a specific string in their name. For example I want all folders deleted with the String "Chrome" And here existing folders:

Chrome_95.0.4638.69

Chrome_96.0.4664.45

I tried it with * but it seems like it works only if you want to delete all files with the same extensions:

import shutil
shutil.rmtree(r'./BR/Chrome*')

Best Regards

Christian


Solution

  • Something like that should work:

    import os
    import re
    import shutil
    for directory in os.listdir() :
        if re.fullmatch('.*Chrome.*', directory):
            shutil.rmtree(directory)