python - 递归删除python中的文件夹

我在删除空目录时遇到问题。这是我的代码:

for dirpath, dirnames, filenames in os.walk(dir_to_search):
    //other codes

    try:
        os.rmdir(dirpath)
    except OSError as ex:
        print(ex)

参数 dir_to_search 是我传递需要完成工作的目录的位置。该目录如下所示:

test/20/...
test/22/...
test/25/...
test/26/...

请注意,以上所有文件夹都是空的。当我运行此脚本时,文件夹 20,25 单独被删除!但是文件夹 2526 不会被删除,即使它们是空文件夹。

编辑:

我得到的异常(exception)是:

[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/29'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/29/tmp'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/28'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/28/tmp'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/26'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/25'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/27'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/27/tmp'

我在哪里做错了?

最佳答案

试试 shutil.rmtree :

import shutil
shutil.rmtree('/path/to/your/dir/')

https://stackoverflow.com/questions/13118029/

相关文章:

python - 我在 python 中遇到关键错误

linux - 如何来回反向搜索?

linux - 查找和复制文件

python - 在 python shell 中按箭头键时看到转义字符

python - python,del或delattr哪个更好?

python - 在python中通过分隔符拆分字符串

linux - 大量文件的快速 Linux 文件计数

linux - 什么进程正在使用我所有的磁盘 IO

c - C 到毫秒是否有替代 sleep 功能?

linux - 使用 awk 保存修改