Deleting the folders in python recursively

125

9

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.

sriram

Posted 2012-10-29T08:20:09.260

Reputation: 2 311

1are you sure they don't have hidden files? – Jeff – 2012-10-29T08:22:09.183

Is an exception or traceback printed? If so - it would help if you added that to the question – Ngure Nyaga – 2012-10-29T08:23:08.790

@Jeff: Yes I'm sure. In fact in my ubuntu machine I tried rmdir /path/to/25th/folder is deleting the entire directory. Which means that directory is an empty one! – sriram – 2012-10-29T08:29:10.320

2

Possible duplicate of How do I remove/delete a folder that is not empty with Python? of both question AND answer

– Trevor Boyd Smith – 2016-10-17T21:27:12.590

Answers

250

Try shutil.rmtree:

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

Tomek

Posted 2012-10-29T08:20:09.260

Reputation: 2 624

4Does the rmtree deleted the entire directory? I guess it is similar to the one rm -Rf $DIR – sriram – 2012-10-29T08:31:55.937

1@GroovyUser Yes – Tomek – 2012-10-29T08:37:22.827

6https://docs.python.org/2/library/shutil.html#shutil.rmtree – Markus Peröbner – 2015-04-04T09:55:06.570

Be careful as rmtree deletes the files too. As asked, the question was how to delete EMPTY directories.The docs for os.walk give an example that almost exactly matches this question:
import os for root, dirs, files in os.walk(top, topdown=False): for name in dirs: os.rmdir(os.path.join(root, name))
– DaveSawyer – 2018-11-30T18:32:23.993

19

The default behavior of os.walk() is to walk from root to leaf. Set topdown=False in os.walk() to walk from leaf to root.

lqs

Posted 2012-10-29T08:20:09.260

Reputation: 1 066

11

Try rmtree in shutil. in python std library

microo8

Posted 2012-10-29T08:20:09.260

Reputation: 1 192

Does the rmtree deleted the entire directory? I guess it is similar to the one rm -Rf $DIR – sriram – 2012-10-29T08:32:37.967

1from docs: "Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception." – microo8 – 2012-10-29T08:36:55.403

4

better to use absolute path and import only the rmtree function from shutil import rmtree as this is a large package the above line will only import the required function.

from shutil import rmtree
rmtree('directory-absolute-path')

Gajender

Posted 2012-10-29T08:20:09.260

Reputation: 64

3

A bit late to the show but here is my pure Pathlib recursive directory unlinker

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

rmdir(pathlib.Path("dir/"))

mitch

Posted 2012-10-29T08:20:09.260

Reputation: 1 142

1

The command (given by Tomek) can't delete a file, if it is read only. therefore, one can use -

import os, sys
from stat import *

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)

Monir

Posted 2012-10-29T08:20:09.260

Reputation: 771

0

Just for the next guy searching for a micropython solution, this works purely based on os (listdir, remove, rmdir). It is neither complete (especially in errorhandling) nor fancy, it will however work in most circumstances.

def deltree(target):
    print("deltree", target)
    for d in os.listdir(target):
        try:
            deltree(target + '/' + d)
        except OSError:
            os.remove(target + '/' + d)

    os.rmdir(target)

Justus Wingert

Posted 2012-10-29T08:20:09.260

Reputation: 365