Python os.rmdir() Method

Python provides the os module for different operating-related functions like removing directories. The os.rmdir() method is provided to remove directories in operating systems. The os.rmdir() can only remove an empty directory and raise OSError if the specified directory is not empty.

os.rmdir() Syntax

The os.rmdir() method has the following syntax.

os.rmdir(PATH)
  • PATH is a directory path. The PATH can not be a file.

Remove Directory

We can remove an empty directory with the os.rmdir() method by providing the directory name with its path. In the following example, we remove or delete the directory “data” which is located inside the “/home/ismail“.

import os

os.rmdir("/home/ismail/data")

Alternatively, we can use relative paths in order to specify the directory. In the following example, we delete the directory which is located in the parent directory.

import os

os.rmdir("../data")

os.rmdir() Errors and Exceptions

As stated previously the os.rmdir() method removes only empty directories and raises an error if the specified directory is not empty. The exception type is OSError type and can be handled with the except keyword. In the following example, we try to delete the “/home/ismail/data” and if it is not an empty directory we handle the error with the try...except statements.

import os

try:
   os.rmdir("/home/ismail/data")
except OSError as error:
   print(error)

Remove Complete Directory Tree with shutil.rmtree()

There are alternative methods to the os.rmdir() method. If a directory is not empty and we need to remove or delete it the os.rmdir() can not be used. We can use the shutil.rmtree() method in order to delete non-empty directories with data or child directories. In the following example, we delete or remove the directory “/home/ismail/data”.

import shutil

shutil.rmtree("/home/ismail/data")

Leave a Comment