2013-07-19 3 views
2

파이썬의 configparser에 대한 설정 방법은 입니다. 설정 파일에 섹션이 없으면 값을 설정 하시겠습니까?섹션없이 Configparser가 설정 됨

다른 방법이 있으면 알려주세요.

감사합니다.

대한 추가 정보 : Name: value 그것은 내가 주어진 이름에 대한 값을 변경하려면 시스템 파일이있다 : 그래서 기본적으로 나는 형식의 설정 파일을 가지고있다. 파서를 수동으로 작성하는 대신 모듈로 쉽게 할 수 있는지 궁금합니다.

+0

ConfigParser는 주로 파일의 _reading_ 설정에 사용하기위한 것이지만, 내용을 추가하거나 변경하려는 것처럼 들립니다. 그게 어떤 섹션도없는 파일을 읽는 것보다 더 어려운 문제입니다 ... – martineau

답변

2

csv 모듈을 사용하면 파일을 구문 분석하고 변경 한 후 파일을 다시 작성하는 작업을 대부분 할 수 있으므로 비교적 쉽게 사용할 수 있습니다. 나는 Using Python's ConfigParser to read a file without section name이라는 제목의 유사한 질문으로 answer 중 하나에서 아이디어를 얻었다.

그러나 파이썬 2 & 3에서 작동하도록 코딩하는 것을 포함하여 여러 가지 변경 작업을 수행했습니다. 키/값 구분 기호를 사용하지 않기 때문에 (기본적으로 콜론이 될 수 있음) 몇 가지 최적화가 이루어졌습니다.

from __future__ import print_function # only for module main() test function 
import csv 
import sys 
PY3 = sys.version_info[0] > 2 

def read_properties(filename, delimiter=':'): 
    ''' Reads a given properties file with each line of the format key=value. 
     Returns a dictionary containing the pairs. 
      filename -- the name of the file to be read 
    ''' 
    open_kwargs = {'mode': 'r', 'newline': ''} if PY3 else {'mode': 'rb'} 
    with open(filename, **open_kwargs) as csvfile: 
     reader = csv.reader(csvfile, delimiter=delimiter, escapechar='\\', 
          quoting=csv.QUOTE_NONE) 
     return {row[0]: row[1] for row in reader} 

def write_properties(filename, dictionary, delimiter=':'): 
    ''' Writes the provided dictionary in key sorted order to a properties 
     file with each line in the format: key<delimiter>value 
      filename -- the name of the file to be written 
      dictionary -- a dictionary containing the key/value pairs. 
    ''' 
    open_kwargs = {'mode': 'w', 'newline': ''} if PY3 else {'mode': 'wb'} 
    with open(filename, **open_kwargs) as csvfile: 
     writer = csv.writer(csvfile, delimiter=delimiter, escapechar='\\', 
          quoting=csv.QUOTE_NONE) 
     writer.writerows(sorted(dictionary.items())) 

def main(): 
    data = { 
     'Answer': '6*7=42', 
     'Knights': 'Ni!', 
     'Spam': 'Eggs', 
    } 

    filename='test.properties' 
    write_properties(filename, data) 
    newdata = read_properties(filename) 

    print('Read in: ') 
    print(newdata) 
    print() 

    with open(filename, 'rb') as propfile: 
     contents = propfile.read() 
    print('File contents: (%d bytes)' % len(contents)) 
    print(repr(contents)) 

    print(['Failure!', 'Success!'][data == newdata]) 

if __name__ == '__main__': 
    main() 
+0

코드가 도움이됩니다. 감사합니다 martineau. –

+0

'PY3 = sys.version_info [0]> 2'를 변경하면 Python 2.6.6, Python 3.4.1 및 Jython 2.7b2와 호환됩니다. 그 버전의 자이 썬에서'sys.version_info'는 튜플을 반환합니다. 귀하의 코드를 보내 주셔서 감사합니다. – Jorge

+0

@ Jorge : 좋은 지적, 고마워. – martineau

0

나는 매우 section-oriented 인 configparser로 그렇게 할 수 없다.

대안은 Michael Foord의 ConfigObj이라는 Voidspace Python 모듈을 사용하는 것입니다. 그는 An Introduction to ConfigObj를 제목 쓴 기사의 The Advantages of ConfigObj 섹션에서, 그것은 말한다 :

ConfigObj의 가장 큰 장점은 단순함이다. 간단한 키 값 쌍이 필요한 구성 파일의 경우에도 ConfigParser는 '섹션'안에 있어야합니다. ConfigObj가 에이 제한이없고이며 구성 파일을 메모리로 읽은 후 멤버에 액세스하는 것은 쉽습니다.

강조 광산.

+0

정보 Martineau에게 감사드립니다. 이미 파이썬에 대체 모듈이 있는지는 알고 계십니까? –

-1

개인적으로 필자는 설정 파일을 XML로하고 싶습니다.

파이썬에서
<?xml version="1.0"?> 
<config> 
    <name>Michael Foord</name> 
    <dob>12th August 1974</dob> 
    <nationality>English</nationality> 
</config> 

, 당신은 다음과 같은 일을하고 값을 얻을 수 있습니다 : 다음과 같은 내용으로 config.xml에라는 파일을 만들 수 있습니다 (비교 목적으로 ConfigObj 기사에서 가져온) 예

우리가 config.xml에를 보면
>>> import xml.etree.cElementTree as etree 
>>> config = etree.parse("config.xml") 
>>> config.find("name").text 
'Michael Foord' 
>>> config.find("name").text = "Jim Beam" 
>>> config.write("config.xml") 

이제 우리는 다음을 참조하십시오

<config> 
    <name>Jim Beam</name> 
    <dob>12th August 1974</dob> 
    <nationality>English</nationality> 
</config> 

일반적인 XML과 동일한 이점을 제공합니다. 사람이 읽을 수 있고 이미 상상할 수있는 모든 프로그래밍 언어로 이미 존재하는 여러 가지 파서가 있으며 그룹화 및 특성을 지원합니다. 설정 파일이 커질 때 추가 보너스로, XML 유효성 검사 (스키마 사용)를 통합하여 런타임 전에 실수를 찾을 수도 있습니다.

+0

사실 나는 이것을 할 능력이 없습니다. 나는 이미 "name : value"와 같은 형식으로 값이있는 .conf 파일을 가지고 있으며 수정하려고합니다. –

+0

@Haros : 이미 가지고있는 .config 파일을 읽기 위해 무엇을 사용하고 있습니까? – martineau

+1

@Haros 추가 접근법에 대한 모든 제약 사항을 질문에 추가해야합니다. –

관련 문제