Skip to content

os.scandir(): add option to yield the given path itself #99454

Open
@calestyo

Description

@calestyo

Feature or enhancement

I think it would be nice if os.scandir() had an option (that defaults to the current behaviour) which makes it also yield the root path itself as given by its path argument.

The benefit would be, that if one has code like e.g.:

def scandirtree(path):
    for p in os.scandir(path):
        if p.is_dir(follow_symlinks=False):
            yield p
            yield from scandirtree(p)
        else:
            yield p

one would also yield path and process that as well (in whatever one does with the generator).

It doesn't seem to be possible right now to write a warpper around scandir which would just yield path first, since one cannot create os.DirEntry objects (see #71983).

Pitch

The above in turn would be the familiar behaviour of many tools, e.g.

$ rm -rf path

also removes the path itself, not just its contents.

find path

also finds path itself.
Etc. pp.

So anyone who wants to implement a tool like these or similar behaviour, would no longer need to specially handle the path itself.

Previous discussion

https://discuss.python.org/t/os-scandir-should-have-an-option-to-also-yield-the-path-itself/18383

Thanks,
Chris.

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions