recursive remove in python
July 7, 2008 Leave a comment
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.