GH-125413: Add pathlib.Path.scandir() method (#126060)

Add `pathlib.Path.scandir()` as a trivial wrapper of `os.scandir()`. This
will be used to implement several `PathBase` methods more efficiently,
including methods that provide `Path.copy()`.
This commit is contained in:
Barney Gale 2024-11-01 01:19:01 +00:00 committed by GitHub
parent d0abd0b826
commit 260843df1b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 114 additions and 11 deletions

View file

@ -1289,6 +1289,35 @@ Reading directories
raised.
.. method:: Path.scandir()
When the path points to a directory, return an iterator of
:class:`os.DirEntry` objects corresponding to entries in the directory. The
returned iterator supports the :term:`context manager` protocol. It is
implemented using :func:`os.scandir` and gives the same guarantees.
Using :meth:`~Path.scandir` instead of :meth:`~Path.iterdir` can
significantly increase the performance of code that also needs file type or
file attribute information, because :class:`os.DirEntry` objects expose
this information if the operating system provides it when scanning a
directory.
The following example displays the names of subdirectories. The
``entry.is_dir()`` check will generally not make an additional system call::
>>> p = Path('docs')
>>> with p.scandir() as entries:
... for entry in entries:
... if entry.is_dir():
... entry.name
...
'_templates'
'_build'
'_static'
.. versionadded:: 3.14
.. method:: Path.glob(pattern, *, case_sensitive=None, recurse_symlinks=False)
Glob the given relative *pattern* in the directory represented by this path,