Package: iterpath
GitHub|PyPI|Issues|Changelogiterpathlets you iterate over a file tree as a single iterator ofpathlib.Pathobjects, eliminating the need to combine lists returned byos.walk()or recursively callPath.iterdir()oros.scandir().
Besides the standardos.walk()options, the library also includes options
for sorting & filtering entries.Installationiterpathrequires Python 3.7 or higher.  Just usepipfor Python 3 (You have pip, right?) to install it:python3 -m pip install iterpathExampleIterate over this library’s source repository, skipping the.gitandtest/datafolders:>>> import os.path
>>> from iterpath import iterpath
>>> def filterer(dir_entry):
...     if dir_entry.name == ".git":
...         return False
...     elif dir_entry.path == os.path.join(".", "test", "data"):
...         return False
...     else:
...         return True
...
>>> with iterpath(".", sort=True, filter_dirs=filterer) as ip:
...     for p in ip:
...         print(p)
...
.github
.github/workflows
.github/workflows/test.yml
.gitignore
LICENSE
MANIFEST.in
README.rst
TODO.md
pyproject.toml
setup.cfg
src
src/iterpath
src/iterpath/__init__.py
src/iterpath/__pycache__
src/iterpath/__pycache__/__init__.cpython-39.pyc
src/iterpath/py.typed
test
test/test_iterpath.py
tox.iniAPITheiterpathmodule provides a single function, also namediterpath:iterpath(dirpath:AnyStr|os.PathLike[AnyStr]=os.curdir,**kwargs)->Iterpath[AnyStr]Iterate through the file tree rooted at the directorydirpath(by default,
the current directory) in depth-first order, yielding the files & directories
within aspathlib.Pathinstances.The return value is both an iterator and a context manager.  In order to ensure
that the internalos.scandir()iterators are closed properly, either call
theclose()method when done or else use it as a context manager like so:with iterpath(...) as ip:
    for path in ip:
        ...Ifreturn_relativeis true, the generatedPathobjects will be relative
todirpath.  Ifreturn_relativeis false (the default) anddirpathis an absolute path, the generatedPathobjects will be absolute;
otherwise, ifdirpathis a relative path, thePathobjects will be
relative and will havedirpathas a prefix.Note that, althoughiterpath()yieldspathlib.Pathobjects, it operates
internally onos.DirEntryobjects, and so any function supplied as thesort_keyparameter or as a filter/exclude parameter must acceptos.DirEntryinstances.Keyword arguments:dirs: bool = TrueWhether to include directories in the outputtopdown: bool = TrueWhether to yield each directory before (True) or after (False) its
contentsinclude_root: bool = FalseWhether to include thedirpathargument passed toiterpath()in the
outputfollowlinks: bool = FalseWhether to treat a symlink to a directory as a directoryreturn_relative: bool = FalseIf true, the generated paths will be relative todirpathonerror:Optional[Callable[[OSError],Any]] = NoneSpecify a function to be called whenever anOSErroris encountered
while iterating over a directory.  If the function reraises the exception,iterpath()aborts; otherwise, it continues with the next directory.  By
default,OSErrorexceptions are ignored.sort: bool = FalseSort the entries in each directory.  WhenFalse, entries are yielded in
the order returned byos.scandir().  WhenTrue, entries are sorted,
by default, by filename in ascending order, but this can be changed via thesort_keyandsort_reversearguments.sort_key:Optional[Callable[[os.DirEntry[AnyStr]],_typeshed.SupportsLessThan]] = NoneSpecify a custom key function for sorting directory entries.  Only has an
effect whensortisTrue.sort_reverse: bool = FalseSort directory entries in reverse order.  Only has an effect whensortisTrue.filter:Optional[Callable[[os.DirEntry[AnyStr]],Any]] = NoneSpecify a predicate to be applied to all files & directories encountered;
only those for which the predicate returns a true value will be yielded
(and, for directories, descended into).Iffilteris specified, it is an error to also specifyfilter_dirsorfilter_files.filter_dirs:Optional[Callable[[os.DirEntry[AnyStr]],Any]] = NoneSpecify a predicate to be applied to all directories encountered; only
those for which the predicate returns a true value will be yielded &
descended intofilter_files:Optional[Callable[[os.DirEntry[AnyStr]],Any]] = NoneSpecify a predicate to be applied to all files encountered; only those for
which the predicate returns a true value will be yieldedexclude:Optional[Callable[[os.DirEntry[AnyStr]],Any]] = NoneSpecify a predicate to be applied to all files & directories encountered;
only those for which the predicate returns a false value will be yielded
(and, for directories, descended into).Ifexcludeis specified, it is an error to also specifyexclude_dirsorexclude_files.exclude_dirs:Optional[Callable[[os.DirEntry[AnyStr]],Any]] = NoneSpecify a predicate to be applied to all directories encountered; only
those for which the predicate returns a false value will be yielded &
descended intoexclude_files:Optional[Callable[[os.DirEntry[AnyStr]],Any]] = NoneSpecify a predicate to be applied to all files encountered; only those for
which the predicate returns a false value will be yieldedIf bothfilterandexcludeare set, a given entry will only be included
iffilterreturns true andexcludereturns false (that is, exclusions
take priority over inclusions), and likewise for the directory- and
file-specific arguments.Warnings:Ifdirpathis a relative path, changing the working directory whileiterpath()is in progress will lead to errors, or at least inaccurate
results.SettingfollowlinkstoTruecan result in infinite recursion if a
symlink points to a parent directory of itself.SelectorsNew in version 0.3.0iterpathalso provides a selection of “selector” classes & constants for
easy construction offilterandexcludearguments.  Selectors are
callables that return true forDirEntry’s whose (base) names match given
criteria.Selectors can even be combined using the|operator:# This only returns entries whose names end in ".txt" or equal "foo.png" or# ".hidden":iterpath(dirpath,filter=SelectGlob("*.txt")|SelectNames("foo.png",".hidden"))# Exclude all dot-directories and VCS directories:iterpath(dirpath,exclude_dirs=SELECT_DOTS|SELECT_VCS_DIRS)The selectors:classSelectNames(*names:AnyStr,case_sensitive:bool=True)SelectsDirEntry’s whose names are one ofnames.  Ifcase_sensitiveisFalse, the check is performed case-insensitively.classSelectGlob(pattern:AnyStr)SelectsDirEntry’s whose names match the given fileglob patternclassSelectRegex(pattern:AnyStr|re.Pattern[AnyStr])SelectsDirEntry’s whose names match (usingre.search()) the given
regular expressionSELECT_DOTSSelectsDirEntry’s whose names begin with a periodSELECT_VCSSelectsDirEntry’s matched by eitherSELECT_VCS_DIRSorSELECT_VCS_FILES(see below)SELECT_VCS_DIRSSelects the following names of version-control directories:.git,.hg,_darcs,.bzr,.svn,_svn,CVS,RCSSELECT_VCS_FILESSelects the following names of version-control-specific files:.gitattributes,.gitignore,.gitmodules,.mailmap,.hgignore,.hgsigs,.hgtags,.binaries,.boring,.bzrignore, and all nonempty filenames that end in,v