Python中的ConfigParser模块使用详解
1.基本的读取配置文件
-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
2.基本的写入配置文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。
3.基本例子
test.conf [sec_a] a_key1 = 20 a_key2 = 10 [sec_b] b_key1 = 121 b_key2 = b_value2 b_key3 = $r b_key4 = 127.0.0.1
parse_test_conf.py import ConfigParser cf = ConfigParser.ConfigParser() #read config cf.read("test.conf") # return all section secs = cf.sections() print 'sections:', secs opts = cf.options("sec_a") print 'options:', opts kvs = cf.items("sec_a") print 'sec_a:', kvs #read by type str_val = cf.get("sec_a", "a_key1") int_val = cf.getint("sec_a", "a_key2") print "value for sec_a's a_key1:", str_val print "value for sec_a's a_key2:", int_val #write config #update value cf.set("sec_b", "b_key3", "new-$r") #set a new value cf.set("sec_b", "b_newkey", "new-value") #create a new section cf.add_section('a_new_section') cf.set('a_new_section', 'new_key', 'new_value') #write back to configure file cf.write(open("test.conf", "w"))
得到终端输出:
sections: ['sec_b', 'sec_a'] options: ['a_key1', 'a_key2'] sec_a: [('a_key1', "i'm value"), ('a_key2', '22')] value for sec_a's a_key1: i'm value value for sec_a's a_key2: 22
更新后的test.conf
[sec_b] b_newkey = new-value b_key4 = 127.0.0.1 b_key1 = 121 b_key2 = b_value2 b_key3 = new-$r [sec_a] a_key1 = i'm value a_key2 = 22 [a_new_section] new_key = new_value
4.Python的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。
设定配置文件test2.conf
[portal] url = http://%(host)s:%(port)s/Portal host = localhost port = 8080
使用RawConfigParser:
import ConfigParser cf = ConfigParser.RawConfigParser() print "use RawConfigParser() read" cf.read("test2.conf") print cf.get("portal", "url") print "use RawConfigParser() write" cf.set("portal", "url2", "%(host)s:%(port)s") print cf.get("portal", "url2")
得到终端输出:
use RawConfigParser() read http://%(host)s:%(port)s/Portal use RawConfigParser() write %(host)s:%(port)s
改用ConfigParser:
import ConfigParser cf = ConfigParser.ConfigParser() print "use ConfigParser() read" cf.read("test2.conf") print cf.get("portal", "url") print "use ConfigParser() write" cf.set("portal", "url2", "%(host)s:%(port)s") print cf.get("portal", "url2")
得到终端输出:
use ConfigParser() read http://localhost:8080/Portal use ConfigParser() write localhost:8080
改用SafeConfigParser:
import ConfigParser cf = ConfigParser.SafeConfigParser() print "use SafeConfigParser() read" cf.read("test2.conf") print cf.get("portal", "url") print "use SateConfigParser() write" cf.set("portal", "url2", "%(host)s:%(port)s") print cf.get("portal", "url2")
得到终端输出(效果同ConfigParser):
use SafeConfigParser() read http://localhost:8080/Portal use SateConfigParser() write localhost:8080

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

파이썬 프로그래밍에서 Python 매개 변수 주석의 대체 사용법, 매개 변수 주석은 개발자가 기능을 더 잘 이해하고 사용하는 데 도움이되는 매우 유용한 기능입니다 ...

Python 스크립트는 특정 위치에서 Cursor 위치로 출력을 어떻게 제거합니까? Python 스크립트를 작성할 때 이전 출력을 커서 위치로 지우는 것이 일반적입니다 ...

내 코드가 API에 의해 데이터를 반환 할 수없는 이유는 무엇입니까? 프로그래밍에서 우리는 종종 API가 호출 될 때 NULL 값을 반환하는 문제를 겪는 경우가 종종 있습니다.

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

파이썬에서 문자열을 통해 객체를 동적으로 생성하고 메소드를 호출하는 방법은 무엇입니까? 특히 구성 또는 실행 해야하는 경우 일반적인 프로그래밍 요구 사항입니다.

Go 또는 Rust를 사용하여 Python 스크립트를 호출하여 실제 병렬 실행을 달성하는 방법은 무엇입니까? 최근에 나는 파이썬을 사용하고 있습니다 ...

Python Binary Library (.WHL) 다운로드 방법은 Windows 시스템에 특정 라이브러리를 설치할 때 많은 Python 개발자가 겪는 어려움을 탐구합니다. 일반적인 해결책 ...
