Customizable Python INI file parser
I recommend using the configparser
library which comes with Python for parsing INI files. However, if you need a highly customizable parser, this code is a good place to start:
def read_ini_config(filename):
config = {}
current_section = None
with open(filename, 'r', encoding="utf-8") as file:
for line in file:
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith(';') or line.startswith('#'):
continue
# Check if it's a section header
if line.startswith('[') and line.endswith(']'):
current_section = line[1:-1]
config[current_section] = {}
else:
# Parse key-value pairs
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
config[current_section][key] = value
return config