Python os.rmdir() Method

The os.rmdir() method in Python is used to remove an empty directory specified in its argument. The directory to be removed must be empty; otherwise, it will throw an OSError.

Syntax

os.rmdir(path, dir_fd=None)

Parameters

Name Description
path It is a string representing the path of the directory to be removed.
dir_fd (Optional) It is a file descriptor with reference to a directory.

Return value

This method does not return any value.

Example 1: Basic usage

Let’s say in our current working directory, there is “dir1”, and inside that, there is an empty directory, “dir2”.

Screenshot of dir2 directory which is empty

Now, let’s step back and check out the “dir1” folder.

Screenshot of dir1 directory

import os

# Removing the created directory
os.rmdir('dir1/dir2')

print("The dir2 is successfully removed")

Output

The dir2 is successfully removed

Screenshot of directory has been removed using os.rmdir()

Example 2: FileNotFoundError: [Errno 2] No such file or directory

Since in the above example, we removed the “dir2” directory, let’s try to remove it again and see what we get as an output.

import os

# Removing the created directory
os.rmdir('dir1/dir2')

print("The dir2 is successfully removed")

Output

FileNotFoundError: [Errno 2] No such file or directory: 'dir1/dir2'

This function throws a FileNotFoundError because we tried to remove a folder that does not exist. 

To handle this type of error, use the try-except block:

import os

try:
  os.rmdir('dir1/dir2')
except FileNotFoundError as error:
  print("Error: Directory does not exist")

Output

Error: Directory does not exist

Example 3: OSError: [Errno 66] Directory not empty:

Let’s create a file called file.txt inside the dir1 directory.

Screenshot of non-empty directory

Now that a directory is non-empty, let’s try to remove this directory.

import os

os.rmdir('dir1')

print('The dir1 is removed')

Output

OSError: [Errno 66] Directory not empty: 'dir1'

Let’s handle this OSError.

import os

try:
  os.rmdir('dir1')
except OSError as error:
  print("Error: Directory does not exist")

Example 4: Using os.path.join() for Path Management

Let’s create only a directory inside the dir1 directory called dir2.

Create a full path to the dir1/dir2 using os.path.join() function and then remove the dir2 directory, which is empty.

import os

dir_name = 'dir2'
parent_dir = 'dir1'

# Creating a full path
full_path = os.path.join(parent_dir, dir_name)

# Removing the directory
try:
  os.rmdir(full_path)
  print("The dir2 has been removed")
except OSError as error:
  print("Error:", error)

Output

The dir2 has been removed

That means dir2 has been deleted, and you can verify it in your file system.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.