본문 바로가기
코딩취미/Python

[파이썬] 환경설정파일 (INI->JSON, INI->YAML) 파일 변환 및 불러오기

by 브링블링 2024. 1. 22.
728x90

환경설정파일 (INI->JSON, INI->YAML) 파일 변환 및 불러오기

개발하는 프로그램에서 환경설정 데이터를 만들어서 사용하기 위한 I/F 구성을 고민했습니다. 일단 가장 보편적인 환경설정 파일인 INI 로 구성해서 동작을 테스트했습니다. 그리고 새로운 데이터 포맷인 JSON과 YAML으로 변형해서 데이터 처리를 진행했습니다. 데이터 포멧이 달라져도 코어코드에서는 딕셔너리 타입으로 접근해서 사용했기때문에 코어코드의 변환은 없이 사용할 수 있었습니다.

 

기본 환경설정파일(INI) 생성

    def create_config(self):
        print("create_config")

        self.config = configparser.ConfigParser()

        self.config["reference_mes_item"] = {}
        self.config["reference_codip_item"] = {}
        self.config["reference_wip_item"] = {}
        self.config["reference_wfstatus_item"] = {}
        self.config["reference_stock_item"] = {}
        #self.config["department_person"] = {}
        self.config["region_person"] = {}
        #self.config["result_sheet_name"] = {}

        default_mes_item = self.config["reference_mes_item"]
        default_codip_item = self.config["reference_codip_item"]
        default_wip_item = self.config["reference_wip_item"]
        default_wfstatus_item = self.config["reference_wfstatus_item"]
        default_stock_item = self.config["reference_stock_item"]
        #default_department = self.config["department_person"]
        default_department = self.config["region_person"]
        #default_result_sheet_name = self.config["result_sheet_name"]

        for index in range(len(MES_DATA_ITEM)):
            item_name = f"item_{index+1}"
            default_mes_item[item_name] = MES_DATA_ITEM[index]
            default_codip_item[item_name] = CODIP_DATA_ITEM[index]

        for index in range(len(WAFER_STATUS_ITEM)):
            item_name = f"item_{index+1}"
            default_wfstatus_item[item_name] = WAFER_STATUS_ITEM[index]

        for index in range(len(WIP_DATA_ITEM)):
            item_name = f"item_{index+1}"
            default_wip_item[item_name] = WIP_DATA_ITEM[index]

        for index in range(len(STOCK_DATA_ITEM)):
            item_name = f"item_{index+1}"
            default_stock_item[item_name] = STOCK_DATA_ITEM[index]

        #for index in range(len(RESULT_SHEET_NAME)):
        #    sheet_name = f"sheet_{index+1}"
        #    default_result_sheet_name[sheet_name] = RESULT_SHEET_NAME[index]

        for index in range(len(DEPARTMENT_ITEM)):
            sheet_name = f"part_{index+1}"
            default_department[sheet_name] = DEPARTMENT_ITEM[index]
            
        
        with open(self.config_file_name, 'w') as configfile:
            self.config.write(configfile)

INI파일을 JSON 파일로 변환

import configparser
import json

# INI 파일을 읽기
config = configparser.ConfigParser()
config.read('MesDoc_config.ini')

# INI 파일을 딕셔너리로 변환
config_dict = {section: dict(config.items(section)) for section in config.sections()}

# 딕셔너리를 JSON 파일로 저장
with open('MesDoc_config.json', 'w') as json_file:
    json.dump(config_dict, json_file, indent=4)

print("INI 파일이 JSON 파일로 변환되었습니다.")
728x90

INI파일을 YAML 파일로 변환

import configparser
import yaml

# INI 파일을 읽기
config = configparser.ConfigParser()
config.read('MesDoc_config.ini')

# INI 데이터를 딕셔너리로 변환
config_dict = {section: dict(config.items(section)) for section in config.sections()}

# 딕셔너리를 YAML 파일로 저장
with open('MesDoc_config.yaml', 'w') as yaml_file:
    yaml.dump(config_dict, yaml_file, default_flow_style=False)

print("INI 파일이 YAML 파일로 변환되었습니다.")

 

새롭게 생성된 파일에서 데이터를 딕셔너리 형태로 만들어서 사용했습니다.

    def get_ini_data(self):
        print("get_ini_data")
        self.config = configparser.ConfigParser()
        self.config.read(self.config_file_name)
        config_section = self.config.sections()
        print(f"config_section = {config_section}")

    def get_json_data(self):
        print("get_json_data")
        with open(self.config_file_name, 'r', encoding='UTF8') as file :
            self.config = json.load(file)
        config_section = self.config.keys()
        print(f"config_section = {config_section}")        


    def get_yaml_data(self):
        print("get_yaml_data")
        with open(self.config_file_name, 'r', encoding="UTF8") as file :
            self.config = yaml.safe_load(file)
        config_section = self.config.keys()
        print(f"config_section = {config_section}")

 

적용결과 비교

서로 다른 데이터 포맷이지만, 최종 사용하는 형태는 딕셔너리타입으로 구성해서 코어코드에서 동일하게 사용할 수 있도록 만들 수 있었습니다.

728x90