Python 3.5's os.scandir(path)
function returns lightweight DirEntry objects that are very helpful with information about files. However, it only works for the immediate path handed to it. Is there a way to wrap it in a recursive function so that it visits all subdirectories beneath the given path?
Return Type: This method returns an iterator of os. DirEntry objects corresponding to the entries in the given directory.
One of the answers may be to use os. walk() to recursively traverse directories. The key here is to use os.
listdir(path='. ') It returns a list of all the files and sub directories in the given path. We need to call this recursively for sub directories to create a complete list of files in given directory tree i.e.
You can scan recursively using os.walk()
, or if you need DirEntry
objects or more control, write a recursive function like scantree()
below:
try: from os import scandir except ImportError: from scandir import scandir # use scandir PyPI module on Python < 3.5 def scantree(path): """Recursively yield DirEntry objects for given directory.""" for entry in scandir(path): if entry.is_dir(follow_symlinks=False): yield from scantree(entry.path) # see below for Python 2.x else: yield entry if __name__ == '__main__': import sys for entry in scantree(sys.argv[1] if len(sys.argv) > 1 else '.'): print(entry.path)
Notes:
'.'
and that kind of thing.follow_symlinks=false
on the is_dir()
calls in recursive functions like this, to avoid symlink loops.On Python 2.x, replace the yield from
line with:
for entry in scantree(entry.path): yield entry
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With