[Python] ConfigParser 를 이용한 config 파싱 예제

Woong·2022년 4월 12일
0

Python / Machine Learning

목록 보기
1/20

configParser

  • INI 파일을 통해 읽고 쓰기를 통해 설정 관리

configParser 로 파일 읽기

[basic]
path=/home/anjinwoong/workspace/
import configParser

def test():

    conf_file = 'test.config'

    config = configparser.ConfigParser()
    config.read(conf_file)

    path = config['basic']['path']

    print(path)


if __name__=="__main__":
    test()

configparser 로 파일에 쓰기

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
                     
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

config['DEFAULT']['ForwardX11'] = 'yes'

with open('example.ini', 'w') as configfile:
  config.write(configfile)
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

reference

0개의 댓글