ConfigParser模組用法

2022-06-10 15:09:11 字數 1317 閱讀 1244

configparser 是python自帶的模組, 用來讀寫配置檔案, 用法及其簡單。 直接上**,不解釋,不多說。

配置檔案的格式是: 包含的叫section,    section 下有option=value這樣的鍵值

配置檔案   test.conf 

[section1]

name =tank

age = 28[section2]

ip = 192.168.1.1port = 8080

python**(python2.7的寫法)

#

-* - coding: utf-8 -* -

import

configparser

conf =configparser.configparser()

conf.read(

"c:\\test.conf")

#獲取指定的section, 指定的option的值

name = conf.get("

section1

", "

name")

print

(name)

age = conf.get("

section1

", "

age"

)print

age#

獲取所有的section

sections =conf.sections()

print

sections

#寫配置檔案

#更新指定section, option的值

conf.set("

section2

", "

port

", "

8081")

#寫入指定section, 增加新option的值

conf.set("

section2

", "

ieport

", "80"

)#新增新的 section

conf.add_section("

new_section")

conf.set(

"new_section

", "

new_option

", "

")#寫回配置檔案

conf.write(open("c:\\test.conf","w"))

python3的寫法稍微有點變動

import

configparser

conf = configparser.configparser()

ConfigParser模組教程

configparser 模組用於操作配置檔案 注 parser漢譯為 解析 之意。配置檔案的格式與windows ini檔案類似,可以包含乙個或多個節 section 每個節可以有多個引數 鍵 值 book title configparser模組教程 time 2012 09 20 22 04 ...

ConfigParser模組教程

目錄 configparser 模組用於操作配置檔案 注 parser漢譯為 解析 之意。配置檔案的格式與windows ini檔案類似,可以包含乙個或多個節 section 每個節可以有多個引數 鍵 值 plain view plain copy book title configparser模組...

configparser模組總結

configparser模組使用來讀取寫入配置檔案的,其配置檔案的結構為 section1 key1 value1 key2 value2 section2 key1 value1 key2 value2其中 包圍的部分為section,是區分各個配置的標誌,下面的值是以key value的形式存在...