Search code examples
pythondirectorydirectory-structure

Python - how do delete content in a complicated folder without changing its structure?


I have a folder with sub-folders, each can contain more sub-folders and so on. I want to delete all the files in all of them, but keeping the directory structure the same. Is there a built-in command or I have to write some recursive function for this using os.listdir?


Solution

  • Shamelessly stolen from the Python Documentation on Files and Directories with the removal of directories omitted:

    # Delete everything reachable from the directory named in "top",
    # assuming there are no symbolic links.
    # CAUTION:  This is dangerous!  For example, if top == '/', it
    # could delete all your disk files.
    import os
    for root, dirs, files in os.walk(top, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))