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?
After some time of practising, I ended up with a code that was in my mind:
def create_folders(zoom):
zoom_min = 1
path_to_folders = 'D:/ms_project/'
if os.path.isdir(path_to_folders):
if not os.listdir(path_to_folders) == []:
for subfolder in os.listdir(path_to_folders):
subfolder_path = os.path.join(path_to_folders, subfolder)
try:
if os.path.isdir(subfolder_path):
shutil.rmtree(subfolder_path)
elif os.path.isfile(subfolder_path):
os.unlink(subfolder_path)
except Exception as e:
print(e)
elif os.listdir(path_to_folders) == []:
print("A folder existed before and was empty.")
elif not os.path.isdir(path_to_folders):
os.mkdir("ms_project")
os.chdir(path_to_folders)
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)
Thanks to everyone who inspired me, especially who replied me to my initial question.