Python os.rmdir() Method



The Python os.rmdir() method removes the directory path. It works only when the directory is empty, otherwise OSError will be raised. If the specified path does not exists, a "FileNotFoundError" is thrown.

To prevent accidental deletion of those directories that contains files, this method does not allow the removal of non-empty directories.

Syntax

Following is the syntax for os.rmdir() method −

os.rmdir(path, *, dir_fd)

Parameters

The Python os.rmdir() method accepts two parameters which are as follows −

  • path − This is the path of the directory, which needs to be removed.

  • dir_fd − It is an optional parameter that is a file descriptor referring to a directory.

Return Value

The Python os.rmdir() method does not return any value.

Example

In this example, we are removing "mydir" directory with the help of rmdir() method.

import os, sys

# listing directories
print ("the dir is: %s" %os.listdir(os.getcwd()))

# removing path
os.rmdir("mydir")

# listing directories after removing directory path
print ("Directory removed successfully")

When we run above program, it produces following result −

the dir is: 
[  'a1.txt','resume.doc','a3.py','mydir','Administrator','amrood.admin' ]
Directory removed successfully

Example

To handle the exceptions that can be thrown during the removal process of directories, we can use the try-except blocks.

import os

try:
   # removing a directory
   os.rmdir("Tutorials")
   print ("Directory removed successfully")
except OSError as exp:
   print(f"Error: {exp.strerror}")

On running the above program, it will produce the following output −

Error: Directory not empty
python_files_io.htm
Advertisements