Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- mysql
- Selenium
- Visual Studio
- Python
- nvidia-smi
- label
- YOLO
- pip
- paramiko
- 오류
- pytorch
- 기타 연주
- 핑거스타일
- Linux
- C
- JSON
- ubuntu
- pandas
- Docker
- VS Code
- 채보
- SSH
- error
- C#
- 프로그래머스
- OpenCV
- Numpy
- 컨테이너
- windows forms
- C++
Archives
- Today
- Total
기계는 거짓말하지 않는다
Python configparser config file 주석(comment) 유지 본문
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")
'Python' 카테고리의 다른 글
Python faulthandler 모듈 Segmentation Fault 진단 (0) | 2025.01.25 |
---|---|
Python colorsys 모듈을 이용한 일정한 분포의 색상 생성 함수 (0) | 2025.01.21 |
Python open 함수 파일 모드(mode) (3) | 2024.09.03 |
Python paramiko 프롬프트 상호작용 invoke_shell (0) | 2024.08.20 |
Python logging 모듈 logger 설정(Settings) (0) | 2024.07.10 |
Comments