I have to keep all the directory which contains files in a specific subdirectory but to delete rest all directories in which subdirectory is empty.
To be more specific here is the structure:
A
|
|--------312311
| |
| |----Recording
| |----a.txt
| |----b.txt
|
|
|--------453453
| |----Recording
| |
| |-------a.mp3
| |----a.txt
| |----b.txt
|
|
|--------566532
| |----Recording
| |----a.txt
| |----b.txt
The subdirectories may or may not contain a file. So I need to delete the whole directory like '312311' & '566532' and only '453453' should be left with all data in it because it has a file in 'Recording' folder which is a specific directory for me.
I saw many posts but it links to many specific file names. Any help will be much appreciated as I need to do many times in a week.
Best Answer
The script below will do exactly as you describe, it:
Looks inside each of the folders for a folder named "Recording"
In an image:
will result in:
The script
To use
delete_empty.py
Run it with the (full!) directory (containinf your subdirs, A in your example) as argument by the command:
That's it.
Explanation
Feeding the content of your folder "A" to the script,
will list its subdirectories (and files). Then:
will try to list the content of each of the (sub)folders, which will raise an error if the item is a file:
or if the folder "Recording" does not exist at all:
If the folder "Recording" exists and is empty, the superior folder is removed:
EDIT
Additionally, as requested in comments, a version that will check for multiple subdirs (names).
In case the directory contains any of the listed (un- empty) subdirs, the directory is kept. Else it will be deleted.
To use
delete_empty.py
Run it with the (full!) directory (containing your subdirs, A in your example) and the names of subdirs as arguments by the command:
That's it.
The script
Note
Please first run on a test directory to make sure it does exactly what you want.