
Removing empty directories
>>> import os >>> os.listdir() ['example.txt'] >>> os.rmdir('example.txt') >>> os.listdir() []
Removing non-empty directories
rmdir( )
works only when a directory is empty. If we have to remove or delete the directory path of non-empty directory, we have to use retree( )
funtion defined in shutil
module.
>>> import os >>> import shutil >>> os.listdir() ['xyz'] >>> shutil.rmtree('xxyz') >>> os.listdir() []
Removing multiple directories at once
To remove multiple directories at once, Python has function removedirs( )
defined in os
module.
Unlike rmdir( )
, removedirs( )
remove all the parent directories mentioned in the directory path recursively until an exception is raised.
Let’s take a deeper look with an example:
Suppose we have a directory z
inside y
, which is child directory of x
.
Now to remove all three directories at once we can use removedirs( )
in following way.
>>> import os >>> os.removedirs('x/y/z')
This will delete the directory path of all x
, y
, and z
if no exception is raised.
First it will remove z
, then it will remove z's
parent directory y
and finally y's
parent directory x
.
If y
is non-empty and hence raises and exception while removing, only x
will be deleted.