天天看點

python之configParser子產品讀寫配置檔案

借鑒:http://www.cnblogs.com/TankXiao/p/3038350.html

configParser是python自帶的子產品,用來讀寫配置檔案

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

配置檔案  test.conf

[section1]

name = tank

age = 28

[section2]

ip = 127.0.0.1

port = 8080

python代碼

#-*- coding:UTF-8 -*-

import configParser

conf = configParser.configParser()

conf.read("c:\\tset.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("sections","port","8081")

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

conf.set("section2", "IEPort", "80")

# 添加新的 section

conf.add_section("new_section")

conf.set("new_section", "new_option", "http://www.cnblogs.com/tankxiao")

轉載于:https://www.cnblogs.com/zzzidea/p/7214273.html