Done

[Python] python config 파일 정리

weasel7 2022. 2. 18. 22:32
728x90

Python config 파일의 종류를 정리했다
본 글을 참고하여 나를 위한 글임으로 자세한 내용은 해당글을 확인하길 바란다

Python config 파일은 4가지 정도로 설정할 수 있다

  • ini, yaml, json, py 순서대로 설명 하겠다

ini

  • ini, conf, cfg 모두 같은 설정파일 ini는 section 개념이 있어 설정을 그룹화할 수 있음

conf.ini

[1st_section]
1st_key=value_1
2nd_key=value_2

[2nd_section]
last_key=value_last

python으로 읽기

from configparser import ConfigParser

config = ConfigParser()
config.load('conf.ini')
print(config['1st_section']['1st_key']) # value_1

Json

xml 대체하는 표준! python의 dict와 유사함

데이터의 type도 인식하기 때문에 Number, string, Boolean, Array, Object, Null로 세분화하여 값 표현가능

우리나라 오픈 데이터 포맷도 json을 표준으로 인정하고 있음 키 - 값 구조의 데이터를 json! 통칭하기도 함

config.json

{
    "1st_key": ["value_1", "value_2"],
    "2nd_key": "value_last"
}

python으로 읽기

import json

with open('conf.json') as f:
    config = json.load(f)
print(config['2nd_key']) # value_last

YAML

구조화된 데이터를 직렬화! 하는데 초점을 둠 - makrdown 문서와 유사

하이픈 불릿으로 열거된 값들이 주어지면 이를 리스트 배열로 인식한다는 특징이 있다

ROS에서 사용

conf.yaml

1st_key: value_1
2nd_key: value_2
last_key:
  - list_value_1
  - list_value_2

Python으로 Yaml 읽기

import yaml

with open('conf.yaml', 'r') as f:
    config = yaml.load(f)
print(config['1st_key']) # value_1

Python versions 3.10 or later yaml.load TypeError
TypeError: load() missing 1 required positional argument: 'Loader' 가 나오고 이에대한 해결책은 2가지가 있습니다.

1. yaml.safe_load(f)

2. yaml.load(f, Loader=yaml.FullLoader) 

Python

py 설정 파일 가능!!!

  • conf.py
config =\
    {
        '1st_key': ['value_1', 'value_2'],
        '2nd_key': 'value_last',
    }
from conf import config

print(config['2nd_key']) # value_last
728x90