有一个python相当于“rm -rf”?

Is there a python equivalent of “rm -rf”?

本问题已经有最佳答案,请猛点这里访问。

我想删除一个文件夹,如果它已经存在,如何删除目录的任何输入,如果它存在?是否有一个相当于"rm-rf"的python?

如果os.path.isdir("./.repo"):shutil.rmtree('./.repo')


你可以用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.

注意:rm-fr路径并不严格等同于shutil.rmtree("path",ignore_errors=true)。rm-fr将删除只读文件,rmtree将不删除。(见@Richard的评论)