Reputation: 5512
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:
Upvotes: 0
Views: 1533
Reputation: 792
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.
Upvotes: 3