Last active
February 19, 2023 02:32
-
-
Save hugoaboud/d30521644dff4cb7c33270c593b1a36c to your computer and use it in GitHub Desktop.
Build a directory tree, including files, for a given path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
def dirtree(path): | |
steps = list(os.walk(path)) | |
def _tree(): | |
_, child_dirs, files = steps.pop(0) | |
obj = { child: _tree() for child in child_dirs } | |
obj['__files__'] = files | |
return obj | |
return _tree() | |
# Output Example: | |
# { | |
# "A": { | |
# "C": { | |
# "D": { | |
# "__files__": [ | |
# "d.txt", | |
# "d1.txt" | |
# ] | |
# }, | |
# "__files__": [ | |
# "c.txt" | |
# ] | |
# }, | |
# "__files__": [ | |
# "a.txt", | |
# "a2.txt", | |
# "a3.txt" | |
# ] | |
# }, | |
# "__files__": [] | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment