[Python] How to delete an element from a folder name

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    Let's say I have a folder that contains a lot of subfolders. These subfolders all have [Extra] at the end of their name.

    Is there a simple way to delete all those [Extra] in one go?

    I tried to adapt a code I found about renaming files, but it didn't work. Something like this:

    import os
    from pathlib import Path

    path = r"C:\Test"
    suffix = "[Extra]"

    for root, dirs, files in os.walk(path, topdown=False):
    for name in dirs:
    if name.endswith(suffix):
    directoryPath = os.path.join(root, name)
    parentDirectory = Path(directoryPath).parent
    os.chdir(parentDirectory)
    os.remove(suffix)

    Continue reading...

Compartilhe esta Página