Delete a specific folder with a path as a parameter in python

278 Views Asked by At

I want to delete a Folder named "testfolder" and all the subfolders and files in it. I want to give the "testfolder" path as a parameter when calling the python file. For example ...... (testfolder location) and there it should delete the "testfolder" when the folder exists

3

There are 3 best solutions below

4
Alihan ÖZ On BEST ANSWER

You can use shutil.rmtree() for removing folders and argparse to get parameters.

import shutil
import argparse
import os

def remove_folder(folder_path='./testfolder/'):
    if os.path.exists(folder_path):
        shutil.rmtree(folder_path)
        print(f'{folder_path} and its subfolders are removed succesfully.')
    else:
        print(f'There is no such folder like {folder_path}')


if __name__ == "__main__":
     parser = argparse.ArgumentParser(description='Python Folder Remover')
     parser.add_argument('--remove', '-r', metavar='path', required=True)

     args = parser.parse_args()

     if args.remove:
         remove_folder(args.remove)

You can save above script as 'remove.py' and call it from command prompt like:

  python remove.py --remove "testfolder"
2
Umutambyi Gad On

I guess this might be what you're looking for

import os
import shutil

pathLocation = # Whatever your path location is
if os.path.exists(pathLocation):
     shutil.rmtree(pathLocation)
else:
    print('the path doesn\'t exist')
0
Umer Rana On

Better to use absolute path and import only the rmtree function from shutil import rmtree as this is a large package the above line will only import the required function.

from shutil import rmtree
rmtree('directory-absolute-path')