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
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"