Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete folders with specific names in Python?

I did not work too much with Python Files I/O and now I want kindly ask your help.

I want to delete all folders that have specific names, e.g. '1', '2', '3', ... I created them with a code:

zoom_min = 1
path_to_folders = 'D:/ms_project/'
def folders_creator(zoom):
     for name in range (zoom_min, zoom + 1):
        path_to_folders = '{0}'.format(name)
         if not os.path.exists(path_to_folders):
             os.makedirs(path_to_folders)

I want my Python code to have a condition which I do not know how to write, that checks if these folders ('1', '2', '3', ...) already exist:

if yes, I want to delete them with all their content and then execute the code above. if not, then just execute the code.

P.S. Does any difference exist between 'directory' and 'folder' based on programming syntax?

like image 320
Taras Avatar asked Jan 24 '26 14:01

Taras


1 Answers

Hope this code helps you figure this out.

You can use the os.walk function to get list of all directory to check if the subfolder (1 or 2 or 3) exsists. Then you can use os.system which essentially allows you to launch cmd commands and delete command is used. This is a crude solution but hope this helps.

import os

# purt r"directorypath" within os.walk parameter.

genobj = os.walk(r"C:\Users\Sam\Desktop\lel") #gives you a generator function with all directorys
dirlist = genobj.next()[1] #firt index has list of all subdirectorys
print dirlist 

if "1" in dirlist: #checking if a folder called 1 exsists
    print "True"


#os.system(r"rmdir /S /Q your_directory_here ")
like image 164
Sam Thomas Avatar answered Jan 26 '26 08:01

Sam Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!