Skip to content

Instantly share code, notes, and snippets.

@mzpqnxow
Created June 3, 2018 03:54
Show Gist options
  • Save mzpqnxow/b7af7cadc4c31dfeff163140075d0e6a to your computer and use it in GitHub Desktop.
Save mzpqnxow/b7af7cadc4c31dfeff163140075d0e6a to your computer and use it in GitHub Desktop.
Create a YaML file from a filesystem structure
#!/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)
@mzpqnxow
Copy link
Author

17:47:26 › python dir2yml.py /usr/local
Dictionary written to local.yaml
17:47:28 › cat local.yaml     
local:
- bin:
  - iface_check_repair.sh
17:47:29 ›

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment