0

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.
maximusdooku
  • 5,242
  • 10
  • 54
  • 94
  • 1
    You can find most of what you need in this post: http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory os.walk() reads through folders recursively. It also distinguishes files from folders. – ma3oun Apr 14 '17 at 09:51
  • @maximusdooku, I hope I have answered what you were asking for ! – Raj Damani Apr 17 '17 at 06:52

1 Answers1

3
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.

Raj Damani
  • 782
  • 1
  • 6
  • 19