Python 3 – os.rmdir() Method
Python offers a lot of modules that can make programming more convenient and easy. One of such modules is the “os” module which is used to handle file and directory operations. With the “os” module, you can create, read, update, and delete files and directories.
In this article, we will be discussing the “os.rmdir()” method. The “os.rmdir()” method is used to remove (or delete) an empty directory. This method comes in handy when you want to delete an empty directory programmatically.
Syntax
import os
os.rmdir(path)
Parameters
The “os.rmdir()” method takes in only one parameter which is the path of the directory that needs to be deleted.
Return Value
The “os.rmdir()” method doesn’t return any value. It raises an error if the directory is not empty or if there is no directory at the specified path.
Example
Let’s look at an example of how to use the “os.rmdir()” method. Let’s assume we have a directory named “mydir” on the desktop and we want to delete it programmatically.
import os
path = "/Desktop/mydir"
os.rmdir(path)
This code will delete the directory named “mydir” which is located on the desktop.
Error Handling
When using the “os.rmdir()” method, there are two possible errors that can occur. The first error is the “OSError” which is raised if the directory is not empty. The second error is the “FileNotFoundError” which is raised if there is no directory at the specified path.
Let’s see an example of how to handle the “OSError” error:
import os
path = "/Desktop/mydir"
try:
os.rmdir(path)
except OSError:
print("Directory is not empty")
This code will print out “Directory is not empty” if the “os.rmdir()” method fails because the directory is not empty.
Now let’s see an example of how to handle the “FileNotFoundError” error:
import os
path = "/Desktop/mydir"
try:
os.rmdir(path)
except FileNotFoundError:
print("Directory not found")
This code will print out “Directory not found” if the “os.rmdir()” method fails because the directory is not found.
Conclusion
Deleting an empty directory using the “os.rmdir()” method is quite simple and straightforward. However, it is important to note that this method can only be used to delete empty directories. If you need to delete a directory that is not empty, you will need to use the “shutil” module. Always remember to handle errors properly so that your program doesn’t crash unexpectedly. I hope you found this article helpful.