rm -rf in python

David Allen s2mdalle at titan.vcu.edu
Sat Feb 24 22:39:35 EST 2001


In article <979er50ij at news1.newsguy.com>, "Noah Spurrier" <noah(a)noah.org>
wrote:

> 
> Your function couldn't work because it was returning early from your 'for'
> loop (in both directory and file deletion).  The fixed code is below. I also
> moved the os.rmdir AFTER the listdir looping, because it makes the code
> cleaner. You don't have to detect if the directory is empty or not. If the
> directory is empty then listdir returns an empty list and the loop does
> nothing. I also replaced:
>      file = '%s%s%s' % (dirname, os.sep, file)
> with:
>      path = os.path.join (dirname, file)
> which does pretty much the same thing...
> 
> Finally I added a dirty shell script to make a bunch of files  and
> directories for testing. The root directory is called 'foodir'.
> 
> Also, consider experimenting with os.path.walk().
> 
> Yours, Noah

Thanks a lot - this is a lot cleaner and shorter
than mine was too.  :)

I had briefly looked at os.path.walk() but I decided
against it because this recursive solution just
seemed cleaner to me than walking through each file
and having specific logic to see if it was a directory
or file, empty or not, etc. and whether or not 
the walk was passing them to me in the right order or
not.  (i.e. if the path /home/user/foo/bar/baz/foo.txt
exists, I'd want to get the paths in this order:

/home/user/foo/bar/baz/foo.txt
/home/user/foo/bar/baz/
/home/user/foo/bar/
/home/user/foo/
/home/user)

Also, I think I'm going to go from dircache.listdir()
to os.listdir() since I don't actually need the 
caching mechanism at all.
-- 
David Allen
http://opop.nols.com/
----------------------------------------
Math is like love - a simple idea but it can get complicated. 
- R. Drabek



More information about the Python-list mailing list