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

Python dlete file or folder code example
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap