0

I have done this before but this program is a bit different,

from io import StringIO
import yaml
import sys

data ='''
asdhklf
SAKDLALKSJDH
rfsudyf48
CBAKJHDSKJAH
'''

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



for index, line in enumerate(fh):  # iterate by-line
    host = line.strip()  # do any needed validation here
    data[host] = {
        "nodename": host,
        "hostname": f"{host}.northamerica.net",
        "username": "rundeck",
        "tags": '`rundeck`',
    }
yaml.dump(data, sys.stdout)

The issue is that when I make it read from a file it always errors out.

I want to make it so that instead of having to copy and paste into the program under the data = ''' it will automatically take the data from a file path you give it.

2
  • how were you trying to read from the file? Commented May 3, 2021 at 18:39
  • What's the error? Commented May 3, 2021 at 18:41

1 Answer 1

1

This code works for me. It's just reading from the file and putting the data into the variable data.

from io import StringIO
import yaml
import sys

# data ='''
# asdhklf
# SAKDLALKSJDH
# rfsudyf48
# CBAKJHDSKJAH
# '''

with open("inputfile123.txt") as inputFile:
    data = inputFile.read()

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

for index, line in enumerate(fh):  # iterate by-line
    host = line.strip()  # do any needed validation here
    data[host] = {
        "nodename": host,
        "hostname": f"{host}.northamerica.cerner.net",
        "username": "rundeck",
        "tags": '`rundeck`',
    }
yaml.dump(data, sys.stdout)
Sign up to request clarification or add additional context in comments.

4 Comments

You can also use file.readlines(), which will return your file as a list of lines.
@NotSirius-A either I used .read() to put it into a string, but '\n'.join(file.readlines()) would work too (though I have no idea why you would do that :) )
Sorry, i phrased that badly. I meant that it's sometimes easier to use readlines(). For example if you have a dataset in a .txt file, then it's much easier to process the data. @Cooluser2189 didn't specify the exact purpose.
@NotSirius-A helpful to have multiple options :)