python - 是否有相当于 "rm -rf"的 python?

标签 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/

相关文章:

python - 表达式 math.sqrt() 是必要的吗?

python - MQTT 客户端不断断开连接

python - 如何通过列表创建类的实例

python - 如何使用 SQLAlchemy + postgreSQL 减少连接数?

python - 合并 2 个表并汇总数据

python - 如何从使用 plot_date 生成的图形中删除点?

python - django 模型中的属性字段未序列化。怎么修?

python - 如何捕获在 IIS、FastCGI 和 WSGI 下运行的 Python 进程的 STDOUT?

python - 有更简单的方法来检测 python 中的元音吗?

python - 在哪里可以下载 PyQT 的安装程序文件?