I have a directory structure a Port ID and within that Port ID directory have sub-directories of their type and within that Port Type directory it may or may not have some .jpg files, such that
Port ID- **11852**---> 20Port_1
---> 25Port_1 ---> 1.jpg
---> 25Port_2
---> 25Port_3 --> abc.jpg
---> 75Port_1
---> 75Port_2 --> pqr.jpg
So the directory name "11852" consist of 6 sub directories inside it, we have only one type of 20Port
so it is _1
at the end of its name, likewise we have 3 types of 25Port
so _1,_2,_3
and so on.
What I wanted to do is go inside each sub-directory of 11852
directory and check if they do consist of any .jpg
files or not, if not then delete that sub- directory
For instance check inside sub-directory 20Port_1
if it contains any .jpg file or not, since it does not have any file inside it delete the folder 20Port_1
.
Now check 25Port_1
since it has a file inside it keep it as it is. Next directory 25_Port_2
it also doesn't have a file inside it so delete it, next directory 25Port_3
this has a file inside(Now here's the catch) keep it as it is but rename it to its previous group type number i.e change name of 25Port_3
to 25Port_2
,
Similarly rename 75Port_2
to 75Port_1
because 75Port_1
doesn;t contains any file inside it.
So finally my directory structure should look like
Port ID- **11852** --> 25Port_1 --> 1.jpg
--> 25Port_2 --> abc.jpg
--> 75Port_1 --> pqr.jpg
I have tried
import os
import shutil
fold_list = os.listdir("D/Port ID Folder/11852")
for m in fold_list:
k=0
if len(os.listdir('D/Port ID Folder/11852/'+fold_list[k])) ==0:
x = (fold_list[k].rsplit('_',1)[0]) == (fold_list[k+1].rsplit('_',1)[0])
if x == False:
shutil.rmtree('D/Port ID Folder/11852/'+m)
else:
val = fold_list[k].rsplit('_',1)[1]
shutil.rmtree('D/Port ID Folder/11852/'+m)
But didn't got the output, Any suggestion
Thanks