Delete folders using os.scandir recursively

Viewed 20

I'm trying to delete folders recursively using os.scandir() something like this

rootdir = '/automation/major/build/testing'
def list_and_delete_dirs(rootdir):
   for dir in os.scandir(rootdir):
       if dir.is_dir():
          directory_path = dir.path
          if os.path.exists(directory_path):
             cmd = (f"sudo rm -rf {directory_path}")
             subprocess.call(cmd,shell=True)
       list_and_delete_dirs(dir)

But it's deleting only the first occurrence for example if there are 5 folders A B C D E, after the first deletion it's throwing this error

ERROR:root:[Errno 2] No such file or directory: '/build/testing/A'
Traceback (most recent call last):
  File "utils/delta_automation/utils/cleanup/deleteOldBuilds.py", line 53, in <module>
    main(args)
  File "utils/delta_automation/utils/cleanup/deleteOldBuilds.py", line 39, in main
    list_and_delete_dirs(rootdir)
  File "utils/delta_automation/utils/cleanup/deleteOldBuilds.py", line 32, in list_and_delete_dirs
    list_and_delete_dirs(dir)
  File "utils/delta_automation/utils/cleanup/deleteOldBuilds.py", line 14, in list_and_delete_dirs
    for dir in os.scandir(rootdir):
FileNotFoundError: [Errno 2] No such file or directory: 'build/testing/A'

It's successfully deleting folder A but not able to go to the next directory, how to fix the code?

0 Answers
Related