rm -rf in python

Noah Spurrier (a) noahnoah.org
Sat Feb 24 18:07:17 EST 2001


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

------------ Version 1 ---------------------------------------------
<pre>
import os, dircache

def recursive_delete(dirname):
	files = dircache.listdir(dirname)
	for file in files:
		path = os.path.join (dirname, file)
		if os.path.isdir(path):
			recursive_delete(path)
		else:
			print 'Removing file: "%s"' % path
			retval = os.unlink(path)
			
	print 'Removing directory:', dirname
	os.rmdir(dirname)
</pre>

------- Script to make test files and directories -----------------
#!/bin/sh
mkdir foodir
cd foodir
echo foo > foofile1
echo foo > foofile2
echo foo > foofile3
mkdir foodir1
mkdir foodir2
cd foodir1
echo foo > foofile1
echo foo > foofile2
echo foo > foofile3
cd ..
cd foodir2
echo foo > foofile1
echo foo > foofile2
echo foo > foofile3
mkdir foodir2_1
mkdir foodir2_2
cd foodir2_2
echo foo > foofile1
echo foo > foofile2
echo foo > foofile3

> I need to write the equivalent of "rm -rf" in python,
> so I wrote this, but I'm having a hard time understanding
> why it's not working.  
> 
> The assumptions that I'm working off of is that
> os.rmdir() will fail on a non-empty directory, and
> that os.unlink() will fail on a directory.  Here's
> the code:
> 
> ...
> and so on, but the file actually still exists after
> the program runs.  The module documentation in python
> doesn't say anything about any particular return
> value signaling an error and not being able to delete
> a file, and all of these calls seem to be returning
> None.  I've programmed in C before, and these syscalls
> should return 0 for success, and != 0 otherwise,
> but does that hold in python?
> 
> Any help would be appreciated.
> -- 
> David Allen
> http://opop.nols.com/
> ----------------------------------------
> Alliance, n.: 
> In international politics, the union of two thieves who have 
> their hands so deeply inserted in each other's pocket that they cannot 
> separately plunder a third. 
> - Ambrose Bierce, "The Devil's Dictionary"


==================================
Posted via http://nodevice.com
Linux Programmer's Site



More information about the Python-list mailing list