2
def checkandremoveboth(): dirpath = "C:\Adialapps\CRMV3', 'C:\Adialapps\CRMV2" if os.path.exists(dirpath) and os.pathisdir(dirpath): shutil.rmtree(dirpath) 

This formatting looks correct but not working?

2
  • 2
    What does "not working" mean? What error message or unexpected behavior do you see? Commented Dec 6, 2018 at 1:39
  • 1
    Also, you have a race condition here. You check that the path exists but there's no reason it can't be removed by a different process after the check, but before the script executes shutil.rmtree. It would be better to use a try/except block to just delete the directories and catch any errors. You can also call it with ignore_errors=true to suppress exceptions if the path doesn't exists, although you do risk hiding other errors, like incorrect permissions. Commented Dec 6, 2018 at 1:43

2 Answers 2

2
import os, shutil def remove_dirs(dirs): for dir in dirs: shutil.rmtree(dir, ignore_errors=True) # https://docs.python.org/3/library/shutil.html#shutil.rmtree dirs = ["C:\Adialapps\CRMV3', 'C:\Adialapps\CRMV2"] remove_dirs(dirs) 
Sign up to request clarification or add additional context in comments.

2 Comments

Did you mean to keep his mismatched parentheses?
I couldn't fully understand the the original code, but the problem seemed clear.
2

A better-way and clean way with loop rather than checking each path manually .

import os def check_and_remove(pathsList): for path in pathsList: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(dir,ignore_errors=True) print("Deleted") else: print(path, " directory not found") dirs_to_delete = [ 'C:\Adialapps\CRMV3', 'C:\Adialapps\CRMV2' ] check_and_remove(dirs_to_delete) 

Comments