Python 如何强制删除非空文件夹?

os.rmdir() 和 os.removedirs() 可以删除文件夹,但有个前提条件是文件夹是空的
据博客所说:
https://blog.csdn.net/T704379675/article/details/55026009

原来,os.removedirs()遍历删除多个文件夹不假,但是,它适用的情景很特殊:
他的工作方式像rmdir()一样,它删除多个文件夹的方式是通过在目录上由深及浅逐层调用rmdir()函数实现的,在确定最深的目录为空目录时(因为rmdir只能移除空目录),调用rmdir()函数,移除该目录,工作对象上移一层目录,如果上次的移除动作完毕后当前目录也变成了空目录,那么移除当前目录。重复此动作,直到遇到一个非空目录为止。

废了一番周折之后,终于找到解决方案:

import shutil
shutil.rmtree(path, ignore_errors=True)

shutil — High-level file operations

高级的文件操作库
不翻译了,自己看吧!

shutil.rmtree(path, ignore_errors=False, onerror=None)

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.

参考链接:
1.https://blog.csdn.net/T704379675/article/details/55026009
2.https://docs.python.org/3.7/library/shutil.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容