1

I have a directory of folders and subfolders that I need to search through to find a certain folder name, "old data", so that I can delete the files within "old data" and delete the folder itself and the files within it (but not it's parent folder). There are 122 folders to search through, with only some of those containing a subfolder named 'old data'. How do I search through each folder for "old data" and delete it? I'm relatively new to python, and the only code I've managed to get is listing the directories so I can visualize which folders have a subfolder named "old data" and which don't:

import os

os.chdir('C:/directory')

for root, dirs, subdirs in os.walk('C:/directory'):
 for d in dirs:
      print os.path.join(root, d)
A Snider
  • 21
  • 1
  • 1
  • 2
  • 1
    So the question boils down to how to delete a directory once you found it? Does [this](https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty-with-python) answer your question? – timgeb Nov 09 '17 at 08:58

2 Answers2

7

See if the below code works for your scenario:

import os
import shutil

for root, subdirs, files in os.walk('C:/directory'):
    for d in subdirs:
        if d == "old data":
            shutil.rmtree(os.path.join(root, d))

shutil.rmtree will delete the entire "old data" directory

Sach
  • 373
  • 3
  • 9
2

following code is for linux environment but shutil.rmtree() is what you need

1 import os                                                                                                                                                             
2 import shutil                                                                  
3                                                                                
4 root = "/home/user/input"                                                     
5 for i in os.walk(root, topdown=False):                                         
6      if i[0].split('/')[-1] == "test3":                                        
7          shutil.rmtree(i[0]) 

os.remove() - to remove file os.rmdir() - to remove empty dir shutil.rmtree() - to remove dir and all its content

TheBeginner
  • 405
  • 5
  • 23