Edit: sample code https://replit.com/@JustinEzequiel/CoralFrighteningSign thanks to JustinEzequiel
This is my current code.
JavaScript
x
18
18
1
import yaml
2
filepath = input("input path to file: ")
3
data = {} # start a new dictionary
4
5
6
with open(filepath) as fh:
7
for index, line in enumerate(fh): # iterate by-line
8
if index % 4 == 1:
9
host = line # do any needed validation here
10
data[host] = {} # start another dict to write to
11
elif index % 4 == 2:
12
host = line.strip()
13
data[host]["hostname"] = line.strip() # host is still the block header!
14
15
with open("output.txt", "w") as fh:
16
yaml.dump(data, fh)
17
18
It outputs something like this
JavaScript
1
8
1
'
2
? 'D32489DJ
3
4
'
5
: hostname: 'D32489DJ
6
7
'
8
(if D32489DJ) was the host name.
I want to make it output something like
JavaScript
1
6
1
D32489DJ:
2
hostname: D32489DJ
3
nodename: D32489DJ
4
username: rundeck
5
tags: 'rundeck'
6
How can I modify my code to make this possible?
Snippet of file path
all you have to do is drag the file into your terminal after you run the program, make a new txt file named whatever you want.
put this exactly as it is line by line
JavaScript
1
6
1
hLKJH3019
2
BNKASDL32
3
dDASJKLH3
4
CNBAhsa32
5
ddkLJASCNjdaskA
6
that’s what it looks like in my file, just random host names that don’t make any sense separated line by line.
Advertisement
Answer
You forgot to string the n
(linebreaks) at the end of each line.
JavaScript
1
34
34
1
from io import StringIO
2
import yaml
3
import sys
4
5
data = '''
6
hLKJH3019
7
aaa
8
dDASJKLH3
9
CNBAhsa32
10
ddkLJASCNjdaskA
11
bbb
12
BNKASDL32
13
dDASJKLH3
14
CNBAhsa32
15
ccc
16
hLKJH3019
17
BNKASDL32
18
dDASJKLH3
19
ddd
20
ddkLJASCNjdaskA
21
'''
22
23
fh = StringIO(data)
24
data = {} # start a new dictionary
25
26
for index, line in enumerate(fh): # iterate by-line
27
if index % 4 == 1:
28
host = line.strip() # do any needed validation here
29
data[host] = {} # start another dict to write to
30
elif index % 4 == 2:
31
data[host]["hostname"] = line.strip() # host is still the block header!
32
33
yaml.dump(data, sys.stdout)
34