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

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.

其他回答

这是我的纯pathlib递归目录解链接器:

from pathlib import Path

def rmdir(directory):
    directory = Path(directory)
    for item in directory.iterdir():
        if item.is_dir():
            rmdir(item)
        else:
            item.unlink()
    directory.rmdir()

rmdir(Path("dir/"))

这个命令(由Tomek给出)不能删除文件,如果它是只读的。因此,我们可以使用-

import os, sys
import stat

def del_evenReadonly(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)

if  os.path.exists("test/qt_env"):
    shutil.rmtree('test/qt_env',onerror=del_evenReadonly)

这里有一个python式和无递归的解决方案

>>> for e in sorted(p.rglob('**/*'), key=lambda v: v.is_dir()):
...     try:
...         e.unlink()
...     except IsADirectoryError:
...         e.rmdir()

rglob()递归地给出路径p中的所有文件和目录。sorted()及其key参数确保结果按文件顺序排列,最后按目录顺序排列。这使得可以先删除所有目录的文件,从而使所有目录为空。

try…除了…Part阻止您使用廉价的if语句。

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

命令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.