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')
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')
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)