700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python os.removedirs() 和shutil.rmtree()(os.removedirs用于删除非空文件夹和子

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

时间:2018-07-18 00:41:40

相关推荐

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

文章目录

shutil.rmtree()os.removedirs()

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 onerroris 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; andexc_info is a tuple returned by sys.exc_info(). If ignore_errorsis 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 intermediateones. Works like rmdir except that, if the leaf directory issuccessfully removed, directories corresponding to rightmost pathsegments will be pruned away until either the whole path isconsumed or an error occurs. Errors during this latter phase areignored -- 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()

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。