Anpassbarer Python-INI-Datei-Parser
Ich empfehle die Verwendung der configparser-Bibliothek, die mit Python zum Parsen von INI-Dateien geliefert wird. Wenn Sie jedoch einen hochgradig anpassbaren Parser benötigen, ist dieser Code ein guter Ausgangspunkt:
ini_parser.py
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 configCheck out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow