Welcome, guest | Sign In | My Account | Store | Cart

This recipe can be used to clean up a directory tree irrespective of whether the directory tree contains non-empty directories. As long as the user has permission to remove the files, this will work.

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
""" removeall.py:

   Clean up a directory tree from root.
   The directory need not be empty.
   The starting directory is not deleted.
   Written by: Anand B Pillai <abpillai@lycos.com> """

import sys, os

ERROR_STR= """Error removing %(path)s, %(error)s """

def rmgeneric(path, __func__):

    try:
        __func__(path)
        print 'Removed ', path
    except OSError, (errno, strerror):
        print ERROR_STR % {'path' : path, 'error': strerror }
            
def removeall(path):

    if not os.path.isdir(path):
        return
    
    files=os.listdir(path)

    for x in files:
        fullpath=os.path.join(path, x)
        if os.path.isfile(fullpath):
            f=os.remove
            rmgeneric(fullpath, f)
        elif os.path.isdir(fullpath):
            removeall(fullpath)
            f=os.rmdir
            rmgeneric(fullpath, f)

There is no support for cleaning a non-empty directory tree in python os module. os.removedirs() cannot be used to clean directories with non-empty sub-directories. I work on windows and many times in the week, need to copy and delete a big file system from the network to my machine. If I perform deletion using Windows Explorer, it takes a long time and also pops up unnecessary dialogs. The python script did it about 60% faster than explorer and about 10% faster than MKS tool-kit's 'rm -rf' command.

4 comments

gyro funch 18 years, 8 months ago  # | flag

Check out the shutil module. I believe the function

shutil.rmtree(path[, ignore_errors[, onerror]])

does the same thing.

stewart midwinter 16 years, 8 months ago  # | flag

yes, that works. Yes, the shuti.rmtree() function does the same thing. But, the recipe supplied could be useful if you need to only delete files based on whether they meet some condition - in that case you don't want to just blow them all away with a single expression.

S

Chad Stryker 14 years, 7 months ago  # | flag

shutil.rmtree has its shortcomings. Although it is true you can use shutil.rmtree() in many cases, there are some cases where it does not work. For example, files that are marked read-only under Windows cannot be deleted by shutil.rmtree(). By importing the win32api and win32con modules from PyWin32 and adding line like "win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this obstacle can be overcome. I used this approach to fix the hot-backup.py script of Subversion 1.4 so it will work under Windows. Thank you for the recipe.

Alia Khouri 12 years, 10 months ago  # | flag

You may be interested in Recipe 576643 which is a permission-based directory/file cleaner.