Skip to content
Advertisement

How to modify the parsing of my Python script

Edit: sample code https://replit.com/@JustinEzequiel/CoralFrighteningSign thanks to JustinEzequiel

This is my current code.

import yaml
filepath = input("input path to file: ")
data = {}  # start a new dictionary


with open(filepath) as fh:
    for index, line in enumerate(fh):  # iterate by-line
        if index % 4 == 1:
            host = line  # do any needed validation here
            data[host] = {}  # start another dict to write to
        elif index % 4 == 2:
            host = line.strip()
            data[host]["hostname"] = line.strip()  # host is still the block header!

with open("output.txt", "w") as fh:
    yaml.dump(data, fh)

It outputs something like this

    '
? 'D32489DJ

  '
: hostname: 'D32489DJ

    '

(if D32489DJ) was the host name.

I want to make it output something like

D32489DJ: 
  hostname: D32489DJ
  nodename: D32489DJ
  username: rundeck
  tags: 'rundeck'

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

hLKJH3019
BNKASDL32
dDASJKLH3
CNBAhsa32
ddkLJASCNjdaskA

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.

from io import StringIO
import yaml
import sys

data = '''
hLKJH3019
aaa
dDASJKLH3
CNBAhsa32
ddkLJASCNjdaskA
bbb
BNKASDL32
dDASJKLH3
CNBAhsa32
ccc
hLKJH3019
BNKASDL32
dDASJKLH3
ddd
ddkLJASCNjdaskA
'''

fh = StringIO(data)
data = {}  # start a new dictionary

for index, line in enumerate(fh):  # iterate by-line
    if index % 4 == 1:
        host = line.strip()  # do any needed validation here
        data[host] = {}  # start another dict to write to
    elif index % 4 == 2:
        data[host]["hostname"] = line.strip()  # host is still the block header!

yaml.dump(data, sys.stdout)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement