recursively removing files and directories

Discussion in 'Python' started by rbt, Jan 16, 2006.

  1. rbt

    rbt Guest

    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
     
    rbt, Jan 16, 2006
    #1
    1. Advertising

  2. rbt

    Fuzzyman Guest

    Fuzzyman, Jan 16, 2006
    #2
    1. Advertising

  3. Wasn't this the example given in the Python manuals? Recursively
    deleting files and directories?

    cheers,

    --Tim
     
    Tim N. van der Leeuw, Jan 16, 2006
    #3
  4. Richie Hindle, Jan 16, 2006
    #4
  5. rbt

    rbt Guest

    Tim N. van der Leeuw wrote:
    > Wasn't this the example given in the Python manuals? Recursively
    > deleting files and directories?


    I don't know... I wrote it without consulting anything. Hope I'm not
    infringing on a patent :)
     
    rbt, Jan 16, 2006
    #5
  6. rbt

    rbt Guest

    rbt, Jan 16, 2006
    #6
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ken
    Replies:
    1
    Views:
    3,747
    Roedy Green
    Dec 2, 2005
  2. Trinity
    Replies:
    1
    Views:
    513
    Peter van Merkerk
    Nov 7, 2003
  3. bahoo
    Replies:
    2
    Views:
    313
    Eli Criffield
    Apr 9, 2007
  4. albert kao
    Replies:
    5
    Views:
    694
    Walter Wefft
    May 16, 2010
  5. Alain.Feler
    Replies:
    3
    Views:
    119
    Ghislain Mary
    May 15, 2005
Loading...

Share This Page