ConfigParser 모듈에 대한 자세한 소개

零下一度
풀어 주다: 2017-07-23 13:45:12
원래의
1538명이 탐색했습니다.

1. 소개

일반적인 구성 문서를 생성하고 수정하는 데 사용됩니다. Python 3.x 버전에서는 현재 모듈의 이름이 configparser로 변경되었습니다.

2. 구성 파일 형식

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no
로그인 후 복사

3. 구성 파일 생성

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['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

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

#写入配置文件
with open('example.ini', 'w') as configfile:
    config.write(configfile)
로그인 후 복사

4. 구성 파일 읽기

1. 노드 읽기 정보

import configparser

config = configparser.ConfigParser()
config.read('example.ini')

# 读取默认配置节点信息
print(config.defaults())

#读取其他节点
print(config.sections())

# 输出
OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])

['bitbucket.org', 'topsecret.server.com']
로그인 후 복사

 

2. 구성 노드 이름이 있는지 확인

print('ssss' in config)
print('bitbucket.org' in config)

#输出
False
True
로그인 후 복사

 

3. 구성 노드의 정보를 읽습니다

print(config['bitbucket.org']['user'])

#输出

hg
로그인 후 복사

 

4. 루프를 통해 구성 노드의 모든 정보를 읽습니다

for key in config['bitbucket.org']:
    print(key, ':', config['bitbucket.org'][key])

#输出

user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes
로그인 후 복사

위 내용은 ConfigParser 모듈에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!