문제

나는 다음과 같습니다.

config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()

열린 파일을 어떻게 닫을 수 있습니까? config.read?

제 경우에는 새 섹션/데이터가 config.cfg 파일, wxtree 위젯을 업데이트합니다. 그러나 한 번만 업데이트하면 config.read 파일을 열어 둡니다.

그리고 우리가 그것에있는 동안 ConfigParser 그리고 RawConfigParser?

도움이 되었습니까?

해결책

사용 readfp 읽는 대신 :

with open('connections.cfg') as fp:
    config = ConfigParser()
    config.readfp(fp)
    sections = config.sections()

다른 팁

ConfigParser.read(filenames) 실제로 당신을 위해 그것을 처리합니다.

코딩하는 동안 나는이 문제를 발견하고 나 자신에게 같은 질문을 묻는 것을 발견했다.

읽는 것은 기본적으로 내가이 리소스를 마친 후에도이 리소스를 닫아야한다는 것을 의미합니다.

파일을 직접 열고 사용하기 위해 제안한 답변을 읽었습니다. config.readfp(fp) 대안으로. 나는 보았다 선적 서류 비치 그리고 실제로는 없다는 것을 알았습니다 ConfigParser.close(). 그래서 조금 더 조사하고 configparser 코드 구현 자체를 읽었습니다.

def read(self, filenames):
    """Read and parse a filename or a list of filenames.

    Files that cannot be opened are silently ignored; this is
    designed so that you can specify a list of potential
    configuration file locations (e.g. current directory, user's
    home directory, systemwide directory), and all existing
    configuration files in the list will be read.  A single
    filename may also be given.

    Return list of successfully read files.
    """
    if isinstance(filenames, basestring):
        filenames = [filenames]
    read_ok = []
    for filename in filenames:
        try:
            fp = open(filename)
        except IOError:
            continue
        self._read(fp, filename)
        fp.close()
        read_ok.append(filename)
    return read_ok

이것은 실제입니다 read() configparser.py 소스 코드의 메소드. 보시다시피, 바닥에서 세 번째 라인, fp.close() 어떤 경우에도 사용 후 열린 리소스를 닫습니다. 이것은 configparser.read ()와 함께 이미 상자에 포함되어 있습니다. :)

차이 ConfigParser 그리고 RawConfigParser 그게 다 ConfigParser "마술처럼"다른 구성 변수에 대한 참조를 "마술 적으로"확장하려고 시도합니다.

x = 9000 %(y)s
y = spoons

이 경우 x 될거야 9000 spoons, 그리고 y 그냥 될 것입니다 spoons. 이 확장 기능이 필요한 경우 문서는 대신 사용하는 것이 좋습니다. SafeConfigParser. 나는 둘 사이의 차이가 무엇인지 모르겠다. 확장이 필요하지 않은 경우 (아마도 그렇지 않을 것입니다) RawConfigParser.

의심을 테스트하려면 사용하십시오 configparser.readfp () 그리고 파일의 개방 및 닫기를 직접 처리합니다. 만들기 readfp 변경이 이루어진 후에 전화하십시오.

config = ConfigParser()
#...on each change
fp = open('connections.cfg')
config.readfp(fp)
fp.close()
sections = config.sections()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top