I am trying to automate a search and delete operation for specific files and folder underneath a specific folder. Below is the folder structure which I have:
Primary Dir
To get you started:
Ideally the folder name and file name I would want to delete is same under every ChildFolder, so the find should happen only one level down the MasterFolder.
One easy way to go through every child folder under MasterFolder
is to loop over [os.listdir]('/path/to/MasterFolder')
. This will give you both files and child folders. You can check them each with os.path.isdir. But it's much simpler (and more efficient, and cleaner) to just try
to operate on them as if they were all folders, and handle the exceptions on non-folders by doing nothing/logging/whatever seems appropriate.
The list you get back from listdir
is just bare names, so you will need os.path.join to concatenate each name to /path/to/MasterFolder
. And you'll need to use it to concatenate "someTxt.txt"
and "someFilesFolder"
as well, of course.
Finally, while you could listdir
again on each child directory, and only delete the file and subdirectory if they exist, again, it's simpler (and cleaner and more efficient) to just try
each one. You apparently already know how to shutil.rmtree
and os.unlink
, so… you're done.
If that "ideally" isn't actually guaranteed, instead of os.listdir
, you will have to use os.walk. This is slightly more complicated, but if you look at the examples, then come back up and read the docs above the examples for the details, it's not hard to figure out.