歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python讀取ini配置文件

Python讀取ini配置文件

日期:2017/3/1 10:30:24   编辑:Linux編程

需求:

寫個項目,用到數據庫,多個地方使用,不能硬編碼。很類似java的properties文件

Python支持ini文件的讀取

涉及模塊:

ConfigParser

xml文件

  1. db_config.ini
  2. [baseconf]
  3. host=127.0.0.1
  4. port=3306
  5. user=root
  6. password=root
  7. db_name=evaluting_sys
  8. [concurrent]
  9. processor=20

對應的python代碼

  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. #author: lingyue.wkl
  4. #desc: use to db ops
  5. #---------------------
  6. #2012-02-18 created
  7. #---------------------
  8. import sys,os
  9. import ConfigParser
  10. class Db_Connector:
  11. def __init__(self, config_file_path):
  12. cf = ConfigParser.ConfigParser()
  13. cf.read(config_file_path)
  14. s = cf.sections()
  15. print 'section:', s
  16. o = cf.options("baseconf")
  17. print 'options:', o
  18. v = cf.items("baseconf")
  19. print 'db:', v
  20. db_host = cf.get("baseconf", "host")
  21. db_port = cf.getint("baseconf", "port")
  22. db_user = cf.get("baseconf", "user")
  23. db_pwd = cf.get("baseconf", "password")
  24. print db_host, db_port, db_user, db_pwd
  25. cf.set("baseconf", "db_pass", "123456")
  26. cf.write(open("config_file_path", "w"))
  27. if __name__ == "__main__":
  28. f = Db_Connector("../conf/db_config.ini")

得到結果:

section: ['concurrent', 'baseconf']
options: ['host', 'db_name', 'user', 'password', 'port']
db: [('host', '127.0.0.1'), ('db_name', 'evaluting_sys'), ('user', 'root'), ('password', 'root'), ('port', '3306')]
127.0.0.1 3306 root root

Copyright © Linux教程網 All Rights Reserved