Skip to content

Instantly share code, notes, and snippets.

@hugoaboud
Last active February 19, 2023 02:32
Show Gist options
  • Save hugoaboud/d30521644dff4cb7c33270c593b1a36c to your computer and use it in GitHub Desktop.
Save hugoaboud/d30521644dff4cb7c33270c593b1a36c to your computer and use it in GitHub Desktop.
Build a directory tree, including files, for a given path
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