Feed on
Posts
Comments

if you try and use os.rmdir to remove a set of nested directories in python, you’ll receive the following error message:

OSError: [Errno 66] Directory not empty:

to skirt this problem, use the shutil module:

import shutil

shutil.rmtree(tree_name)


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

2 Responses to “recursively remove directories in python”

  1. on 11 Dec 2009 at 1:24 pm kevin cline

    This fails if any files are read-only.

  2. on 06 Aug 2012 at 5:04 am GF

    Extremely simple bit of code to remove a directory recursively. Simply feed it the path of the top-level directory to remove, and off it goes. As presented, there is no error-checking; failure at any point will stop the function and raise an IOError.

    import os
    def rm_rf(d):
    for path in (os.path.join(d,f) for f in os.listdir(d)):
    if os.path.isdir(path):
    rm_rf(path)
    else:
    os.unlink(path)
    os.rmdir(d)

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.