recursively removing files and directories

rbt rbt at athop1.ath.vt.edu
Mon Jan 16 09:36:02 EST 2006


What is the most efficient way to recursively remove files and directories?

Currently, I'm using os.walk() to unlink any files present, then I call 
os.walk() again with the topdown=False option and get rid of diretories 
with rmdir. This works well, but it seems that there should be a more 
efficient way. Here are my function definitions:

def remove_files(target_dir):
     # This attempts to remove _all_ files from a directory.
     # Use with caution on directories that store temporary files.

     for root, dirs, files in os.walk(target_dir):
         for f in files:

             try:
                 # Make attributes normal so file can be deleted.
                 win32api.SetFileAttributes(os.path.join(root, f), 
win32con.FILE_ATTRIBUTE_NORMAL)
             except:
                 pass

             try:
                 # Try to delete the file.
                 os.unlink(os.path.join(root, f))
             except:
                 pass

def remove_dirs(target_dir):
     # This attempts to remove _all_ sub directories from a directory.
     # Use with caution on directories that store temporary information.

     for root, dirs, files in os.walk(target_dir, topdown=False):
         for d in dirs:

             try:
                 # Make attributes normal so dir can be deleted.
                 win32api.SetFileAttributes(os.path.join(root, d), 
win32con.FILE_ATTRIBUTE_NORMAL)
             except:
                 pass

             try:
                 # Try to delete the directory.
                 os.rmdir(os.path.join(root, d))
             except:
                 pass



More information about the Python-list mailing list