2

I want to delete a folder if is already present,Any inputs on how to delete a dir if it exists?Is there a python equivalent of "rm -rf" ?

if os.path.isdir('./.repo'): shutil.rmtree('./.repo')

user2341103
  • 2,333
  • 5
  • 20
  • 19

1 Answers1

9

You can use shutil.rmtree

shutil.rmtree(path[, ignore_errors[, onerror]])

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.

If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo. The first parameter, function, is the function which raised the exception; it will be os.path.islink(), os.listdir(), os.remove() or os.rmdir(). The second parameter, path, will be the path name passed to function. The third parameter, excinfo, will be the exception information return by sys.exc_info(). Exceptions raised by onerror will not be caught.

Changed in version 2.6: Explicitly check for path being a symbolic link and raise OSError in that case.

Note: rm -fr path is not strictly equivalent to shutil.rmtree("path", ignore_errors = True). rm -fr will remove readonly files, rmtree will not. (see @Richard's comment below)

Community
  • 1
  • 1
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 1
    I post it's a dupe before you post this, yet you get 60 points and I get a helpful flag... Interesting point system here :P, considering this is a near-direct copy of the selected answer of my linked thread. – jdero Jul 10 '13 at 00:07
  • @jdero: There's only one simple answer to this question, so I'm not sure how else it should look. – Blender Jul 10 '13 at 00:20
  • Ouch, I save the downvotes for answers that are very wrong. For the record, I didn't click through to the dupe until after I posted this. besides link only answers are discouraged nowdays. – John La Rooy Jul 10 '13 at 00:28
  • 2
    Note: rm -fr _path_ is not strictly equivalent to shutil.rmtree("_path_", ignore_errors = True). rm -fr will remove readonly files, rmtree will not. I found this on windows 10 python 2.7.15 – Richard Jun 07 '18 at 08:31
  • Thanks Richard. I've added your note to my answer – John La Rooy Jun 07 '18 at 22:38