python 读取配置文件config_python中读取配置文件ConfigParser
在程序中使用配置文件來靈活的配置一些參數(shù)是一件很常見的事情,配置文件的解析并不復(fù)雜,在python里更是如此,在官方發(fā)布的庫(kù)中就包含有做這件事情的庫(kù),那就是ConfigParser,這里簡(jiǎn)單的做一些介紹。
ConfigParser解析的配置文件的格式比較象ini的配置文件格式,就是文件中由多個(gè)section構(gòu)成,每個(gè)section下又有多個(gè)配置項(xiàng),比如:
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
_______________________________________________________________________________________________________________________________
#!/usr/bin/python
#coding:utf-8
import ConfigParser
import string,os,sys
cf = ConfigParser.ConfigParser()
#讀取配置文件
cf.read("test.conf")
#返回section,即[]中的內(nèi)容
s = cf.sections()
print 'section:', s
#返回db section中的選項(xiàng)
o = cf.options("db")
print 'options:',o
#以列表形式返回db section中選項(xiàng)和值
v = cf.items("db")
print 'db:',v
print '-'*60
db_host = cf.get("db","db_host")
db_port = cf.getint("db","db_port")
db_user = cf.get("db","db_user")
db_pass = cf.get("db","db_pass")
#返回整型
threads = cf.getint("concurrent","thread")
processors = cf.getint("concurrent","processor")
print "db_host:", db_host
print "db_port:", db_port
print "db_user:", db_user
print "db_pass:", db_pass
print "thread:", threads
print "processor:", processors
#修改一個(gè)值,再寫回去
cf.set("db","db_pass","test")
cf.write(open("test.conf","w"))
總結(jié)
以上是生活随笔為你收集整理的python 读取配置文件config_python中读取配置文件ConfigParser的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 财务报表审计_python
- 下一篇: python有什么优点_Python是什