Python .rmdir()

Christine_Yang's avatar
Published Apr 1, 2022Updated Aug 21, 2023
Contribute to Docs

The Python .rmdir() method allows the user to delete a folder if it exists in the system or computer and does not contain other folders or files.

Note: A FileNotFoundError is raised if the directory is not found.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

This method is provided by the os module which must be imported beforehand.

import os

os.rmdir("folder_name")

os.rmdir("folder_path")

The .rmdir() method works in the following ways:

  • A "folder_name" that will be successfully deleted if the folder exists in the current directory.
  • A "folder_path" can also be passed if it exists outside of the current directory.

Files can be removed using the .remove() method.

Example

Use .rmdir() to delete the myfolder folder:

import os
# Delete folder in current directory
os.rmdir("myfolder")
# Delete folder in another directory
os.rmdir("/path/to/myfolder")

Codebyte Example

In this example the ./project directory is deleted using the .rmdir() method:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours