언어&플랫폼/python 2015. 3. 17. 18:45



설정파일, 섹션, 옵션 생성

import ConfigParser


config = ConfigParser.RawConfigParser()

config.add_section('Section1')

config.set('Section1', 'an_int', '15')

config.set('Section1', 'a_bool', 'true')

config.set('Section1', 'a_float', '3.1415')

config.set('Section1', 'baz', 'fun')

config.set('Section1', 'bar', 'Python')

config.set('Section1', 'foo', '%(bar)s is %(baz)s!')


with open('example.cfg', 'wb') as configfile:

    config.write(configfile)  ##마지막에 꼭 write 해줘야 한다


example.cfg 내용

[Section1]

an_int = 15

a_bool = true

a_float = 3.1415

baz = fun

bar = Python

foo = %(bar)s is %(baz)s!


설정파일 읽기

config = ConfigParser.RawConfigParser()

config.read('example.cfg')


섹션리스트 가져오기

>>> config.sections()

['Section1']


섹션 추가

config.add_section('testadsec')


섹션 제거

config.remove_section('testadsec')


섹션존재 확인

>>> config.has_section('Section1')

True


해당섹션의 옵션, 옵션값  가져오기

>>> config.items('Section1')

[('an_int', '15'), ('a_bool', 'true'), ('a_float', '3.1415'), ('baz', 'fun'), ('bar', 'Python'), ('foo', '%(bar)s is %(baz)s!')]


해당섹션의 옵션만 가져오기

>>> config.options('Section1')

['an_int', 'a_bool', 'a_float', 'baz', 'bar', 'foo']


옵션 얻기

config.get('Section1', 'an_int')

getint('Section1', 'an_int')        #옵션이 인트형일때만 가져옴

getfloat('Section1', 'an_int')      #옵션이 프로트형일때만

getboolean('Section1', 'an_int')   #옵션이 불린형일때만


옵션 변경

config.set('Section1', 'an_int', 2015)


옵션 제거

config.remove_option('Section1', 'an_int')


옵션 배열 설정/읽기

--설정--

a = [1,2,3,4,5]

config.set('Section1', 'an_int', a)

--읽기--

a = json.loads( config.get('Section1', 'an_int'))

(참고 : http://stackoverflow.com/questions/335695/lists-in-configparser)


주석 적기

config.set('Section1', 'an_int', '# 주석은 "#"나 ";" 이다')

config.set('Section1', 'an_int', '15')






doc(13.2 ConfigParser) <- 정리 내용 

https://docs.python.org/2/library/configparser.html#examples


doc(14,2 configparser)

: https://docs.python.org/3/library/configparser.html



'언어&플랫폼 > python' 카테고리의 다른 글

[python] 파이썬 로깅모듈 (펌)  (0) 2015.03.24
[python] full traceback 쓰기  (0) 2015.03.24
[python] 리스트 랜덤 선택  (0) 2015.01.20
[python] time 관련  (0) 2015.01.06
shell과 pipe 실행하기(subprocess)  (0) 2014.03.21
posted by cozyboy
: