Recursively Deleting Files and Subdirectories


for file in dirList:     os.remove(dirPath + "/" + file) for dir in emptyDirs:     os.rmdir(dir)

To recursively delete files and subdirectories in Python, use the walk(path) function in the os module. For a more detailed description of the walk function, refer to the "Walking the Directory Tree" section earlier in this chapter.

The walk function will automatically create a list of tuples representing the directories that need to be deleted. To recursively delete a tree, walk through the list of directories and delete each file contained in the files list (third item in the tuple).

The trick is removing the directories. Because a directory cannot be removed until it is completely empty, the files must first be deleted and then the directories must be removed in reverse order, starting with the deepest subdirectory.

The example in del_tree.py shows how to use the os.walk(path) function to walk a directory tree and delete the files, and then recursively remove the subdirectories.

import os emptyDirs = [] path = "/trash/deleted_files" 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]) #Enumerate the entries in the tree tree = os.walk(path) for directory in tree:     removeDirectory(directory) #Remove the empty directories for dir in emptyDirs:     print "Removing " + dir     os.rmdir(dir)


del_tree.py

Deleting files in /trash/deleted_files Deleting 102.ini Deleting 103.ini Deleting 104.ini Deleting 105.ini Deleting 106.ini Deleting 107.ini Deleting 108.ini Deleting 109.ini Deleting files in/trash/deleted_files\Test Deleting 111.ini Deleting 114.ini Deleting 115.ini Deleting files in/trash/deleted_files\Test\Test2 Deleting 112.ini Deleting 113.ini Removing /trash/deleted_files\Test\Test2 Removing /trash/deleted_files\Test Removing /trash/deleted_files


Output from del_tree.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net