deltree function
François Pinard
pinard at iro.umontreal.ca
Mon Aug 28 12:58:34 EDT 2000
[Arkaitz]
> Is there a deltree-like function in the Python standard library? I have
> been looking at os.removedirs(), but it won't delete non-empty
> directories. I'd like to delete a whole tree, with files and directories
> mixed, as rm -rf does in Unix. Any hint?
Hello, Arkaitz. As others suggested, the simplest is to execute the shell
command `rm -rf' from within your Python program.
However, if I wanted a pure Python solution, I would slightly modify a
script I wrote to clean out a file hierarchy from the empty directories
it contains, which script is attached to this message. The modification,
untested, would be to add a loop at the beginning of the `walker' script,
so it starts like this:
def walker(dummy, directory, bases):
for base in bases[:]:
name = os.path.join(directory, base)
if os.path.isfile(name) or os.path.islink(name):
os.remove(name)
bases.remove(base)
while not bases:
# etc.
Maybe that some code would also be needed to handle the cases where
permissions are not sufficient to remove files or directories.
-------------- next part --------------
#!/usr/bin/env python
# Copyright ? 2000 Progiciels Bourbeau-Pinard inc.
# Fran?ois Pinard <pinard at iro.umontreal.ca>, 2000.
"""\
Remove empty directories in the given directory hierarchies.
Usage: rmdir-empty [DIRECTORY]...
If not directory is given, the current directory is implied.
"""
import os, sys
def main(*arguments):
if arguments:
for argument in arguments:
os.path.walk(argument, walker, None)
else:
os.path.walk('.', walker, None)
def walker(dummy, directory, bases):
while not bases:
sys.stdout.write("Removing %s\n" % directory)
os.rmdir(directory)
directory, base = os.path.split(directory)
if not directory or not os.path.isdir(directory):
break
bases = os.listdir(directory)
if __name__ == '__main__':
apply(main, sys.argv[1:])
-------------- next part --------------
--
Fran?ois Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list