기계는 거짓말하지 않는다

Python configparser config file 주석(comment) 유지 본문

Python

Python configparser config file 주석(comment) 유지

KillinTime 2025. 1. 21. 22:41

Python의 configparser 모듈로 config file을 읽고 쓰면 config file의 주석은 유지되지 않는다.

주석을 유지해야 할 때, 가능하도록 간단히 구현한 예시이다.

import configparser
def read_config_with_comments(file_path):
"""config file과 config file의 line을 함께 read"""
with open(file_path, 'r') as file:
lines = file.readlines()
config = configparser.ConfigParser(allow_no_value=True)
config.read(file_path)
return config, lines
def write_config_with_comments(config, lines, output_file, space_around_delimiters=False):
"""config file 주석 유지"""
existing_sections = set(config.sections())
written_sections = set()
current_section = None
delimiters = "=" if not space_around_delimiters else " = "
with open(output_file, 'w', encoding='utf-8') as file:
for line in lines:
stripped = line.strip()
if stripped.startswith("#") or not stripped:
file.write(line)
continue
if stripped.startswith("[") and stripped.endswith("]"):
current_section = stripped.strip("[]")
written_sections.add(current_section)
file.write(line)
continue
if "=" in line and current_section:
key = line.split("=", 1)[0].strip()
if current_section in config and key in config[current_section]:
value = config[current_section][key]
file.write(f"{key}{delimiters}{value}\n")
else:
file.write(line) # Write original line if no updated value found
else:
file.write(line)
for section in existing_sections - written_sections:
file.write(f"\n[{section}]\n")
for key, value in config[section].items():
file.write(f"{key}{delimiters}{value}\n")
for section in written_sections:
for key, value in config[section].items():
if key not in [line.split("=", 1)[0].strip() for line in lines if "=" in line]:
file.write(f"{key}{delimiters}{value}\n")
Comments