I have a config file in following format:
# some comment
keyword1=value1
keyword2=value2
...
where values could be text strings (e.g. /usr/local/lib/...), numbers, IP addresses (10.10.10.1/24). I'd like to be able to parse the configuration and store internally (may be as dictionary).
I'm newbie with python
, in bash
I used source my_config.cfg
.
what is the right way parse/store config options in python? As a newbie, I'd start with:
with open("my_config.cfg", "rt") as f:
...
but what do I do next, call f.redline()
in a loop until end of file?
CodePudding user response:
def parse_cfg(filename):
data = {}
with open(filename) as f:
for line in f:
if line.startswith("#"):
continue
if "=" in line:
key, value = line.split("=")
data[key.strip()] = value.strip()
return data
You can add custom logic to this.