How to delete a dir or folder using Python code


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 ...

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.