changeset 175:506d895a8500

Implement cutils.util.walk.Scandir as a wrapper for os.scandir()
author Franz Glasner <fzglas.hg@dom66.de>
date Sat, 11 Jan 2025 12:20:11 +0100
parents fc1055878775
children 7f5d05a625fd
files cutils/util/walk.py
diffstat 1 files changed, 61 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/cutils/util/walk.py	Fri Jan 10 15:34:50 2025 +0100
+++ b/cutils/util/walk.py	Sat Jan 11 12:20:11 2025 +0100
@@ -220,6 +220,36 @@
         # Yield after recursion if going bottom up
         yield top, fsobjects
 
+
+    class ScanDir(object):    # noqa: E303   too many blank lines
+
+        """An :func:`os.scandir` wrapper that is always an iterator and
+        a context manager.
+
+        """
+
+        __slots__ = ("_scandir_it", )
+
+        def __init__(self, path):
+            super(ScanDir, self).__init__()
+            self._scandir_it = os.scandir(path)
+
+        def __iter__(self):
+            return self
+
+        def __next__(self):
+            return WalkDirEntry.from_direntry(next(self._scandir_it))
+
+        if PY2:
+            next = __next__
+
+        def __enter__(self):
+            return self
+
+        def __exit__(self, *args, **kwds):
+            if hasattr(self._scandir_it, "close"):
+                self._scandir_it.close()
+
 else:
 
     def _walk(root, top, follow_symlinks):
@@ -260,3 +290,34 @@
             yield from _walk(root, top + (wd.name,), follow_symlinks)
         # Yield after recursion if going bottom up
         yield top, fsobjects
+
+
+    class ScanDir(object):    # noqa: E303   too many blank lines
+
+        """An :func:`os.scandir` wrapper that is always an iterator and
+        a context manager.
+
+        """
+
+        __slots__ = ("_listdir_it", "_path")
+
+        def __init__(self, path):
+            super(ScanDir, self).__init__()
+            self._listdir_it = iter(os.listdir(path))
+            self._path = path
+
+        def __iter__(self):
+            return self
+
+        def __next__(self):
+            return WalkDirEntry.from_path_name(self._path,
+                                               next(self._listdir_it))
+
+        if PY2:
+            next = __next__
+
+        def __enter__(self):
+            return self
+
+        def __exit__(self, *args, **kwds):
+            pass