Search code examples
pythonglob

How can I delete contents of a folder but keep the folder?


I have seen several questions here, but all of them seem to delete the folder as well.

How can I delete only the contents of a particular folder, but keep the folder itself.

Preferably for two conditions:

  1. Contents
  2. Deletes recursively under all all subfolders. But keeps the main folder.

Solution

  • import os
    def functToDeleteItems(fullPathToDir):
       for itemsInDir in os.listdir(fullPathToDir):
            if os.path.isdir(os.path.join(fullPathToDir, itemsInDir)):
                functToDeleteItems(os.path.isdir(os.path.join(fullPathToDir, itemsInDir)))
            else:
                os.remove(os.path.join(fullPathToDir,itemsInDir))
    

    Here function "functToDeleteItems" will take one argument that is "fullPathToDir" which will contain full path of the folder whose content you wan to delete. It will recursively call itself it if find any folder inside it and if found any file then delete it.