Skip to content

os.walk() example of an implementation of shutil.rmtree() is incomplete #126055

@vwheeler63

Description

@vwheeler63

Documentation

In this section:

https://docs.python.org/3.9/library/os.html?highlight=os%20walk

there is a code example at the bottom that claims to be "a simple implementation of shutil.rmtree()". However it is incomplete. Reason: shutil.rmtree() also removes the passed directory whereas the code shown will not. To make it complete, add this line at the end of it after the top (highest) for loop:

os.rmdir(top)

That will make the whole code example look like this:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

os.rmdir(top)

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc direasy

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions