recursive remove in python

In the book Programming Python’, an entire chapter is dedicated to recursive copyting of directories, recursive deletion, etc.  He uses the os tools to accomplish this.

The reason something like this is necessary is the fact that the os tools do not have a built-in recusive delete.  For example, if in my current directory I had a folder named ‘test2’, I would get the following error when trying to remove it.

>>> os.removedirs(‘./test2’)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “/usr/lib/python2.5/”, line 184, in removedirs
OSError: [Errno 39] Directory not empty: ‘./test2’

The book addresses this by doing a walk and deleting all the files first.  There is an easier way.

>>> import shutil
>>> shutil.rmtree(‘./test2’)

In fact, the shutil also include utilities for common recursive tasks that are also addressed in programming python – such as recursively copys and moves.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: