python os.removedirs() 和shutil.rmtree()(os.removedirs用于删除非空文件夹和子文件夹、shutil.rmtree用于删除文件夹下所有文件夹和文件)

shutil.rmtree()

shutil.rmtree() 表示递归删除文件夹下的所有子文件夹和子文件。

def rmtree(path, ignore_errors=False, onerror=None):
    """Recursively delete a directory tree. 递归删除目录树。

    If ignore_errors is set, errors are ignored; otherwise, if onerror
    is set, it is called to handle the error with arguments (func,
    path, exc_info) where func is platform and implementation dependent;
    path is the argument to that function that caused it to fail; and
    exc_info is a tuple returned by sys.exc_info().  If ignore_errors
    is false and onerror is None, an exception is raised.

	如果设置了ignore_errors,错误将被忽略; 
	否则,如果设置了onerror,则调用该函数以使用参数(func,path,exc_info)来处理错误,其中func与平台和实现有关; 
	path是导致该函数失败的参数。 而exc_info是sys.exc_info()返回的元组。 
	如果ignore_errors为false,onerror为None,则会引发异常。

    """

因此如果想删除E盘下某个文件夹,可以用

shutil.rmtree('E:\\myPython\\image-filter\\test', ignore_errors=True)

这样 test 文件夹内的所有文件(包括 test 本身)都会被删除,并且忽略错误。

os.removedirs()

def removedirs(name):
    """removedirs(name)

    Super-rmdir; remove a leaf directory and all empty intermediate
    ones.  Works like rmdir except that, if the leaf directory is
    successfully removed, directories corresponding to rightmost path
    segments will be pruned away until either the whole path is
    consumed or an error occurs.  Errors during this latter phase are
    ignored -- they generally mean that a directory was not empty.

	超级rmdir; 删除叶子目录和所有空的中间目录。 
	类似于rmdir的工作方式,不同之处在于,如果成功删除了叶目录,将删除最右边路径段所对应的目录,
	直到使用完整个路径或发生错误为止。 在后面的阶段中的错误将被忽略-它们通常意味着目录不是空的。

    """

注意:os.removedirs()只能删除子文件夹中的空文件夹,非空无法删除,参见:Python学习:纠错笔记:详解os.removedirs(path)的正确用法

参考文章:python中的 os.mkdir和os.mkdirs,os.rmdir()和os.removedirs()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dontla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值