os.rmdir() method is used to remove an empty directory from the system. It deletes only empty folders and raises an error if the directory contains files or subdirectories. This method is available in the os module and is commonly used for basic directory management tasks.
Example: In this example, os.rmdir() removes an empty directory named demo_folder.
import os
os.rmdir("demo_folder")
print("Directory removed")
Output
Directory removed
Explanation: os.rmdir("demo_folder") deletes the empty directory named demo_folder.
Syntax
os.rmdir(path, *, dir_fd=None)
Parameters:
- path: Path of the empty directory to remove.
- dir_fd (optional): File descriptor referring to a directory. Default is None.
Return Value: This method does not return anything.
Examples
Example 1: In this example, an empty directory named test_dir is removed using os.rmdir().
import os
os.rmdir("test_dir")
print("Directory removed successfully")
Output
Directory removed successfully
Explanation: os.rmdir("test_dir") deletes the empty folder test_dir.
Example 2: In this example, a complete directory path is created using os.path.join() and then removed.
import os
p = "/home/user/docs"
d = "data"
path = os.path.join(p, d)
os.rmdir(path)
print("Directory deleted")
Output
Directory deleted
Explanation: os.path.join(p, d) combines the parent path and folder name into a single directory path.
Example 3: In this example, try-except is used to handle errors that may occur while deleting a directory.
import os
try:
os.rmdir("sample")
print("Directory removed")
except OSError as e:
print("Error:", e)
Output
Error: [Errno 2] No such file or directory: 'sample'
Explanation: If the directory is not empty or inaccessible, OSError is raised and handled inside the except block.