In order to delete a dir/folder using Python code we can make use of the below there modules,
Example 1: using os module to delete an empty directory
import os
dir = "/Users/code2care/PycharmProjects/pythonProject/mydir/"
if os.path.exists(dir):
if len(os.listdir(dir)) != 0:
print("Directory is not empty")
else:
os.rmdir(dir)
print("Directory: " + dir + " deleted ...")
else:
print("Directory not found: " + dir)
Note that before deleting the directory it should be empty or else you will get OSError: [Errno 66] Directory not empty
Example 2: using shutil module to delete an non-empty directory
import shutil
import os
dir = "/Users/code2care/PycharmProjects/pythonProject/mydir/"
if os.path.exists(dir):
shutil.rmtree(dir)
print("Directory: " + dir + " deleted ...")
else:
print("Directory not found: " + dir)
Output:
Directory: /Users/code2care/PycharmProjects/pythonProject/mydir/ deleted ...

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!