Home > other >  Deleting a target folder in many subfolders with python
Deleting a target folder in many subfolders with python

Time:10-22

i have a folder X with many (over 500) subfolders in it. In those subfolders there is sometimes a subfolder TARGET that i want to delete. I was considering using a script for doing this.

i am not python expert but i tried to make this script, before using it risking to lose files i'd need, can you please check if it is correct?? thanks

import os
import shutil
dir = '/Volume/X'
targetDir = 'myDir'

for subdir, dirs, files in os.walk(dir):
    dirpath = subdir
    if dirpath.exists() and dirpath.is_dir():
    shutil.rmtree(dirpath)

CodePudding user response:

Here it is, I fixed your code and made it a bit more useful so anyone can use it :) enjoy

#coded by antoclk @ [email protected]
import os
import shutil

#in dir variable you should put the path you need to scan
dir = '/Users/YOURUSERNAME/Desktop/main' 
#in target variable you should put the exact name of the folder you want to delete. Be careful to use it, it will delete all the files and subfolders contained in the target dir.
target = 'x'

os.system('cls') 
os.system('clear')

print('Removing ' target ' folder from ' dir ' and all its subfolders.')

for dirpath, dirnames, filenames in os.walk(dir):
    for item in dirnames:
        fullPath = os.path.join(dirpath, item)
        #print(os.path.join(dirpath, item))
        if item == 'target':
            print('deleting ' fullPath)
            shutil.rmtree(fullPath)

print('Task completed!')
  • Related