Created
June 3, 2018 03:54
-
-
Save mzpqnxow/b7af7cadc4c31dfeff163140075d0e6a to your computer and use it in GitHub Desktop.
Create a YaML file from a filesystem structure
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
#!/usr/bin/env python2 | |
# -*- coding: utf-8 -*- | |
from __future__ import print_function | |
import os | |
import sys | |
import yaml | |
def dir_to_dict(path): | |
directory = dict() | |
for dirname, dirnames, filenames in os.walk(path): | |
dn = os.path.basename(dirname) | |
directory[dn] = [] | |
if dirnames: | |
for d in dirnames: | |
directory[dn].append(dir_to_dict(path=os.path.join(path, d))) | |
for f in filenames: | |
directory[dn].append(f) | |
else: | |
directory[dn] = filenames | |
return directory | |
if len(sys.argv) == 1: | |
p = os.getcwd() | |
elif len(sys.argv) == 2: | |
p = os.path.abspath(sys.argv[1]) | |
else: | |
sys.stderr.write("Unexpected argument {}\n".format(sys.argv[2:])) | |
try: | |
with open("{}.yaml".format(os.path.basename(p)), "w") as f: | |
try: | |
yaml.dump(dir_to_dict(path=p), f, default_flow_style=False) | |
print("Dictionary written to {}.yaml".format(os.path.basename(p))) | |
except Exception as e: | |
print(e) | |
except Exception as e: | |
print(e) |
Author
mzpqnxow
commented
Feb 28, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment