os.walk and recursive deletion

Martin Marcher martin at marcher.name
Sun Oct 28 17:00:21 CET 2007


27 Oct 2007 17:38:10 GMT, Marc 'BlackJack' Rintsch <bj_666 at gmx.net>:
> On Sat, 27 Oct 2007 18:07:44 +0200, Martin Marcher wrote:
> > 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.
>
> `os.walk()` is itself diving recursivly into the subdirectories…

True but isn't the problem that I need either backtracking to remember
which directories are empty and thus can be deleted or that I need to
do another recursion (like in my function) which returns as soon as
the "new root" is deleted or at least empty?

I mean having a directory structure with 3 subdiretories, each of them
has files in it

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

I call it recursively here because I

* either need to backtrack to remember which directories are empty (and leafs)
* or I just recurse my function which yields an OSError because a
directory the original os.walk will visit doesn't exist anymore
because some recursion already deleted it.

(correct me if I'm wrong - but I'd like to stick with os.walk for this
as an exercise)

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

Nice function but not part of my exercise :) - No it isn't homework
just doing it to play around.

thanks
martin

PS: as I'm writing this i just discovered that I missed the
topdown=False argument for os.walk. Playing a bit with it the docs
seem to say that is more what I want than topdown=True

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours


More information about the Python-list mailing list