Skip to content

Instantly share code, notes, and snippets.

@nicolasguzca
Created April 4, 2017 21:02
Show Gist options
  • Save nicolasguzca/49d95015053cac9daac9e42b71d07ad5 to your computer and use it in GitHub Desktop.
Save nicolasguzca/49d95015053cac9daac9e42b71d07ad5 to your computer and use it in GitHub Desktop.
A simple python script that outputs to a file the contents of a directory ( name and file type)
#this is the way to call the script and save it to a file
#python script.py > ../predicas.json
#!/usr/bin/env python
import os
import errno
def path_hierarchy(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
'path': path,
}
try:
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
]
except OSError as e:
if e.errno != errno.ENOTDIR:
raise
hierarchy['type'] = 'file'
return hierarchy
if __name__ == '__main__':
import json
import sys
try:
directory = sys.argv[1]
except IndexError:
directory = "."
print(json.dumps(path_hierarchy(directory), indent=2, sort_keys=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment