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/os.py”, line 184, in removedirs
rmdir(name)
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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s