-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsplit-yaml
More file actions
executable file
·42 lines (37 loc) · 1.43 KB
/
split-yaml
File metadata and controls
executable file
·42 lines (37 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python3
# import libraries to use
import argparse
import os
import yaml
# create argument parser that makes it easy to define positional, required and optional arguments
# it also has a help functionality and usage message built in
parser = argparse.ArgumentParser(
description="Split a multi-document YAML file into multiple separate files."
)
parser.add_argument(
"--rm", help="remove YAML source file after splitting it up", action="store_true"
)
required_args = parser.add_argument_group("required named arguments")
required_args.add_argument(
"-f", "--file", help="the YAML source file to split up", required=True
)
required_args.add_argument(
"-k",
"--key",
help="the key in each YAML document whose value will be used for the new filename <key-value>.yaml",
required=True,
)
args = parser.parse_args()
# open source file for reading, automatically closed
# in the end by using the 'with' keyword
with open(args.file, "r") as source_file:
# loop through all YAML documents contained in source file
# and create a new file for each of them
# with the value of the given key as the file name
for document in yaml.safe_load_all(source_file):
file_name = document[args.key].lower() + ".yaml"
with open(file_name, "w") as new_file:
yaml.dump(document, new_file, sort_keys=False)
# remove YAML source file if --rm flag was specified
if args.rm:
os.remove(args.file)