<分区>
我想删除一个文件夹,如果它已经存在,关于如何删除一个目录(如果它存在)的任何输入?是否有与“rm -rf”等效的 python?
如果 os.path.isdir('./.repo'): shutil.rmtree('./.repo')
标签 python
<分区>
我想删除一个文件夹,如果它已经存在,关于如何删除一个目录(如果它存在)的任何输入?是否有与“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 path 并不严格等同于 shutil.rmtree("path", ignore_errors = True)。 rm -fr 将删除只读文件, rmtree 不会。 (请参阅下面@Richard 的评论)
关于python - 是否有相当于 "rm -rf"的 python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17560253/