mirror of
https://github.com/python/cpython.git
synced 2025-10-21 22:22:48 +00:00
gh-90385: Add pathlib.Path.walk()
method (GH-92517)
Automerge-Triggered-By: GH:brettcannon
This commit is contained in:
parent
e4d3a96a11
commit
c1e929858a
5 changed files with 338 additions and 1 deletions
|
@ -1321,6 +1321,49 @@ class Path(PurePath):
|
|||
|
||||
return self
|
||||
|
||||
def walk(self, top_down=True, on_error=None, follow_symlinks=False):
|
||||
"""Walk the directory tree from this directory, similar to os.walk()."""
|
||||
sys.audit("pathlib.Path.walk", self, on_error, follow_symlinks)
|
||||
return self._walk(top_down, on_error, follow_symlinks)
|
||||
|
||||
def _walk(self, top_down, on_error, follow_symlinks):
|
||||
# We may not have read permission for self, in which case we can't
|
||||
# get a list of the files the directory contains. os.walk
|
||||
# always suppressed the exception then, rather than blow up for a
|
||||
# minor reason when (say) a thousand readable directories are still
|
||||
# left to visit. That logic is copied here.
|
||||
try:
|
||||
scandir_it = self._scandir()
|
||||
except OSError as error:
|
||||
if on_error is not None:
|
||||
on_error(error)
|
||||
return
|
||||
|
||||
with scandir_it:
|
||||
dirnames = []
|
||||
filenames = []
|
||||
for entry in scandir_it:
|
||||
try:
|
||||
is_dir = entry.is_dir(follow_symlinks=follow_symlinks)
|
||||
except OSError:
|
||||
# Carried over from os.path.isdir().
|
||||
is_dir = False
|
||||
|
||||
if is_dir:
|
||||
dirnames.append(entry.name)
|
||||
else:
|
||||
filenames.append(entry.name)
|
||||
|
||||
if top_down:
|
||||
yield self, dirnames, filenames
|
||||
|
||||
for dirname in dirnames:
|
||||
dirpath = self._make_child_relpath(dirname)
|
||||
yield from dirpath._walk(top_down, on_error, follow_symlinks)
|
||||
|
||||
if not top_down:
|
||||
yield self, dirnames, filenames
|
||||
|
||||
|
||||
class PosixPath(Path, PurePosixPath):
|
||||
"""Path subclass for non-Windows systems.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue