python 递归删除目录_递归删除python中的文件夹

I have problem in deleting the directories that are empty. I have the code like this:

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

//other codes

try:

os.rmdir(dirpath)

except OSError as ex:

print(ex)

The argument dir_to_search is where I'm passing the directory where the work need to be down. That directory looks like this:

test/20/...

test/22/...

test/25/...

test/26/...

Note that all the above folders are empty. When I run this script the folders 20,25 alone gets deleted! But the folders 25 and 26 aren't deleted, even though they are empty folders.

Edit:

The exception that I'm getting are:

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

Where I'm making the mistake.

Thanks in advance.

解决方案

Try shutil module:

import shutil

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值