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


Top Hashtags:

Advertisements

Advertisements




Advertisements