os.walk and recursive deletion

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat Oct 27 13:38:10 EDT 2007


On Sat, 27 Oct 2007 18:07:44 +0200, Martin Marcher wrote:

> Hello,
> 
> I'm playing around with os.walk and I made up del_tree(path) which I
> think is correct (in terms of the algorithm, but not as python wants
> it :)).

It's not correct in terms of the algorithm if you take the algorithm of
`os.walk()` into the equation.

> Here goes the script, as far as I tested it it runs fine in test mode.
> Now that is just use the print statements like attached below. as soon
> as os.rmdir and os.unlink are involved the iterator chokes. How do I
> get around that, or what should I use to be able to recursively delete
> everything under a certain subdir?

> #--snip
> import sys
> import os
> import unittest
> 
> def del_tree(path):
>    walker = os.walk(path)

`os.walk()` is itself diving recursivly into the subdirectories…

>    for entry in walker:
>       cwd = entry[0]
>       subdirs = entry[1]
>       files = entry[2]
>       print "Checking directory: %s" %(cwd, )
>       if files:
>          for file in files:
>             file = os.path.join(cwd, file)
>             print "The file is now: %s" % (file, )
>             #os.unlink(file)
>          print "OK directory %s has no more files, checking for
> subdirs..." % (cwd, )
>       else:
>          print "OK directory %s NEVER HAD FILES, checking for
> subdirs..." % (cwd, )
>       if not subdirs:
>          print "We can delete: %s" % (cwd, )
>          #os.rmdir(cwd)
>       else:
>          for subdir in subdirs:
>             subdir = os.path.join(cwd, subdir)
>             print "We need to recurse into: %s" % (subdir, )
>             del_tree(subdir)

…and here you are calling the your function recursively which then calls
again `os.walk()` on that subdirectory.  That's a little bit too much.

Just use `os.listdir()` (and `os.path.isdir()`) in your recursive function.

>    #os.rmdir(path)
>    print "Removing: %s" % (path, )
> #--snap

Or `shutil.rmtree()`.  :-)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list