1. 程式人生 > >python之configParser模塊讀寫配置文件

python之configParser模塊讀寫配置文件

pytho 配置 添加 print name imp 配置文件 所有 con

借鑒: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")

python之configParser模塊讀寫配置文件