Created
April 4, 2017 21:02
-
-
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 file contains hidden or 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
#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