Python에서 configparser 를 사용하면 .ini 파일을 쉽게 읽고 쓸 수 있습니다.

* (참고) .ini 파일을 읽으려고 할때 찾고자 하는 Section이 없을 경우 파일에 대항 Section 혹은 key값을 추가하는 코드입니다!!
import configparser
import os
def IniWrite(section, key, Value, path):
WritePrivateProfileString(section, key, Value, path)
def IniRead(section, key, default, filePath):
val = GetPrivateProfileString(section, key, default, filePath)
return val
# Set value
def WritePrivateProfileString(section, key, val, filePath):
configFile = configparser.ConfigParser()
configFile.read(filePath)
try:
configFile.set(section, key, val)
except configparser.NoSectionError:
configFile.add_section(section)
configFile.set(section, key, val)
except TypeError:
configFile.set(section, key, str(val))
except:
pass
finally:
with open(filePath, 'w') as file:
configFile.write(file)
# Get value
def GetPrivateProfileString(section, key, default, filePath):
val = None
configFile = configparser.ConfigParser()
configFile.read(filePath)
try:
val = configFile[section][key]
except:
IniWrite(section, key, default, filePath)
val = default
return val
PATH = r"C:\Users\user\Desktop";
INIFILE = os.path.join(PATH, "INIFile_python.ini");
# .ini 파일 쓰기
IniWrite("Section1", "key1-1", "value1-1", INIFILE);
IniWrite("Section1", "key1-2", "value1-2", INIFILE);
IniWrite("Section2", "key2-1", "value2-1", INIFILE);
IniWrite("Section2", "key2-2", "value2-2", INIFILE);
# .ini 파일 읽기
v1 = IniRead("Section1", "key1-1", "value", INIFILE);
v2 = IniRead("Section2", "key2-1", "value", INIFILE);
print("Section key1-1 : " + v1);
print("Section key2-1 : " + v2);
# 만약에 해당하는 key가 없을 경우 예시
v4 = IniRead("Section", "key4", "value", INIFILE);
print("Section key4 : " + v4);
< C# 으로 .ini 파일 읽고 쓰기 >
[C#] .ini 파일의 개념과 사용 방법
.ini 파일의 개념과 GetPrivateProfileString, WritePrivateProfileString 사용 방법 알아보기 .ini 파일은속성을 구성하는 특성 및 섹션에 대한 공개 키를 포함하는 컴퓨터 프로그램에 대한 메시지 구성 문서 입
mssil-7.tistory.com
< 참고 자료 >
configparser — Configuration file parser
Source code: Lib/configparser.py This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows ...
docs.python.org
'프로그래밍 언어 > Python' 카테고리의 다른 글
| [Python] 가상환경(Virtual Environment)의 개념과 사용법 (Windows) (0) | 2024.07.25 |
|---|---|
| [Python] TCP/IP 소켓 통신 (Server/Client) (2) | 2024.07.24 |
| [Python] Python 개발 환경 구축 (Windows) (0) | 2024.06.27 |