diff options
author | Barney Gale <barney.gale@gmail.com> | 2024-11-01 01:19:01 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-11-01 01:19:01 (GMT) |
commit | 260843df1bd8a28596b9a377d8266e2547f7eedc (patch) | |
tree | db6186d963dee64b6448445ea726a9e611453813 /Doc | |
parent | d0abd0b826cfa574d1515c6f8459c9901939388f (diff) | |
download | cpython-260843df1bd8a28596b9a377d8266e2547f7eedc.zip cpython-260843df1bd8a28596b9a377d8266e2547f7eedc.tar.gz cpython-260843df1bd8a28596b9a377d8266e2547f7eedc.tar.bz2 |
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()`.
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/library/pathlib.rst | 29 | ||||
-rw-r--r-- | Doc/whatsnew/3.14.rst | 6 |
2 files changed, 35 insertions, 0 deletions
diff --git a/Doc/library/pathlib.rst b/Doc/library/pathlib.rst index 4380122..b6fb365 100644 --- a/Doc/library/pathlib.rst +++ b/Doc/library/pathlib.rst @@ -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, diff --git a/Doc/whatsnew/3.14.rst b/Doc/whatsnew/3.14.rst index 7f9e310..48314f9 100644 --- a/Doc/whatsnew/3.14.rst +++ b/Doc/whatsnew/3.14.rst @@ -380,6 +380,12 @@ pathlib (Contributed by Barney Gale in :gh:`73991`.) +* Add :meth:`pathlib.Path.scandir` to scan a directory and return an iterator + of :class:`os.DirEntry` objects. This is exactly equivalent to calling + :func:`os.scandir` on a path object. + + (Contributed by Barney Gale in :gh:`125413`.) + pdb --- |