python3使用configparser解析配置文件


http://www.jb51.net/article/87402.htm

需要注意的是每一個字段后面的值外面沒有引號,切記,自己第一次配置時,加了引號,搞了半天 沒找到錯誤,,

在用Python做開發的時候經常會用到數據庫或者其他需要動態配置的東西,硬編碼在里面每次去改會很麻煩。Python自帶有讀取配置文件的模塊ConfigParser,使用起來非常方便。

ini文件
ini配置文件格式:

2016626174140238.png (273×249)

 

讀取配置文件:

1
2
3
4
5
6
7
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read( 'dbconf.ini' )       # 文件路徑
name = conf.get( "section1" , "name" ) # 獲取指定section 的option值
print name
sex = conf.get( "section1" , "sex" # 獲取section1 的sex值
print age

輸出:

1
2
jhao
male


寫入配置文件:

1
2
3
4
5
6
7
8
9
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read( 'dbconf.ini' )
 
conf. set ( "section1" , "name" , "jhao104" )    # 修改指定section 的option
conf. set ( "section1" , "age" , "21" )       # 增加指定section 的option
conf.add_section( "section3" )         # 增加section
conf. set ( "section3" , "site" , "oschina.net" # 給新增的section 寫入option
conf.write( open ( 'dbconf.ini' , 'w' ))

輸出:

2016626174242767.png (288×355)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM