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

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单独被删除!但是文件夹25和26没有被删除,即使它们是空文件夹。

编辑:

我得到的例外是:

[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'

我哪里错了?


当前回答

命令os。Removedirs是一个工具,如果你只寻找一个路径来删除,例如:

os.removedirs("a/b/c/empty1/empty2/empty3")

将删除empty1/empty2/empty3,但保留a/b/c(假设c有一些其他内容)。

    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.

其他回答

命令os。Removedirs是一个工具,如果你只寻找一个路径来删除,例如:

os.removedirs("a/b/c/empty1/empty2/empty3")

将删除empty1/empty2/empty3,但保留a/b/c(假设c有一些其他内容)。

    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.

对于Linux用户,您可以简单地以python方式运行shell命令

import os
os.system("rm -r /home/user/folder1  /home/user/folder2  ...")

如果遇到任何问题,请使用rm -rf代替rm -r 但是记住f会强制删除目录。

其中rm代表移除,-r代表递归,-rf代表递归+强制。

注意:不管目录是否为空,它们都会被删除。

试试shutil.rmtree:

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

os.walk()的默认行为是从根目录遍历到叶目录。在os.walk()中设置topdown=False从叶到根。

尝试使用Python标准库中的shutil中的rmtree()