How to delete a directory

Delete a directory


#!/usr/bin/env python# from  w w  w . j a va 2s  .c o m

import os

os.rmdir('example')

Recursively Deleting Files and Subdirectories


import os#  w w  w. j a  v a2  s.  c o  m

emptyDirs = []
path = "c:/"

def deleteFiles(dirList, dirPath):
    for file in dirList:
        print "Deleting " + file
        os.remove(dirPath + "/" + file)

def removeDirectory(dirEntry):
    print "Deleting files in " + dirEntry[0]
    deleteFiles(dirEntry[2], dirEntry[0])
    emptyDirs.insert(0, dirEntry[0])

tree = os.walk(path)
for directory in tree:
    removeDirectory(directory)

for dir in emptyDirs:
    print "Removing " + dir
    os.rmdir(dir)




















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module