본문 바로가기
프로그램

[파이썬] ini 파일 사용. 쉽게 사용 할 수 있는 함수

by 오디세이99 2022. 9. 27.
728x90
반응형

ini 를 다루려면 configparser package가 있지만 안정적으로 사용하려면 많은 코드를 사용해야 했습니다.

그래서 편하게 사용하도록 다음과 같이 만들었습니다.

 

import configparser

def ini_get(ini_file, section, item):
    ini = configparser.ConfigParser()
    ini.read(ini_file)

    # print(ini.sections())
    rtn = ''
    if section in ini.sections():  # 섹션명이 있는지 확인
        if item in ini[section]:  # 항목명이 있는지 확인
            rtn = ini[section][item]

    return rtn


def ini_set(ini_file, section,item,value):
    ini = configparser.ConfigParser()
    ini.read(ini_file)

    if type(value) == int or type(value) == float:
        value = str(value)

    if section in ini.sections():   # 섹션명이 있는지 확인
        # if item in ini[section]:    # 항목명이 있는지 확인
        ini[section][item] = value   # 새로운 항목으로 기록
    else:                            # section 이 없으면 section/item 만듬
        ini[section] = {}            # 새로운 section 만듬
        ini[section][item] = value   # 항목 및 값 등록

    with open(ini_file, 'w') as configfile:
        ini.write(configfile)

 

사용 방법

# 쓰기
ini_file= 'my_Test2.ini'

ini_set(ini_file,'section01','item01',123)
ini_set(ini_file,'section01','item02',234)
ini_set(ini_file,'section01','item03','345')


# 읽기
rtn = ini_get(ini_file, 'section02', 'item21')
728x90
반응형

댓글