如何递归删除python中的文件夹?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (437)

我在删除空目录方面有问题。我有这样的代码:

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/...

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

异常如下:

[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模块:

import shutil
shutil.rmtree('/path/to/your/dir/')
用户回答回答于

os.walk()就是从根路径到叶子路径。若topdown=Falseos.walk()从一叶子路径走到根路径。

扫码关注云+社区

领取腾讯云代金券