Parse config file and create json object using Python

Viewed 64

I have a directory of config files, each config file has a line like this:

DOMAIN domainname.com

I need to be able to extract everything after DOMAIN and store it in a json object.

I can match the line I need like this:

d = re.findall(^DOMAIN.*, mystring)

I can add that to a dict like this:

dict = {
       "config": {
            "domains": [
               d,
            ]
        }
}

This works but only for the first DOMAIN. How would I find all occurrences of DOMAIN and add it to the domains array?

1 Answers

Assuming all these domain config files are in a config dir whcih only contains files with a single line like DOMAIN <domain>, you could do something like this:

import os

domains = []
for file in os.listdir('./config'):
    with open(file) as f:
        _, d = f.read().strip().split()
        domains.append(d)

then you set the value of domains inside this dictionnary

Related