You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
I have the very same need. I've written an os.scandir() wrapper capable of returning the root directory, but as I'm unable to construct an os.DirEntry object to represent it (#71983), I have to return my own PseudoDirEntry object in that one case, which is a messy solution.
An optional new os.scandir() behavior to return path would be welcome, or I'd happily settle for the ability to instantiate os.DirEntry.
In the meanwhile, does anyone know of an ugly hack that would persuade the existing os.DirEntry implementation to provide an object for an arbitrary path?
calestyo
changed the title
os.scandir(): add option to yielt the given path itself.
os.scandir(): add option to yield the given path itself
Apr 7, 2023
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 itspath
argument.The benefit would be, that if one has code like e.g.:
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 yieldpath
first, since one cannot createos.DirEntry
objects (see #71983).Pitch
The above in turn would be the familiar behaviour of many tools, e.g.
also removes the
path
itself, not just its contents.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.
The text was updated successfully, but these errors were encountered: