2022年 11月 6日

python解析配置文件

最近有个python小项目,有一堆文件需要处理。所以将文件位置写入配置文件中,顺便写了一个解析配置文件的类,仅供大家参考,需要的同学请拿走

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. #-----------------------------------------------------
  4. # author: wanglei
  5. # date : 20160321
  6. # desc : 解析配置文件
  7. # pram : 配置文件位置
  8. #-----------------------------------------------------
  9. import ConfigParser
  10. class confParse(object):
  11. def __init__(self,conf_path):
  12. self.conf_path = conf_path
  13. self.conf_parser = ConfigParser.ConfigParser()
  14. self.conf_parser.read(conf_path)
  15. def get_sections(self):
  16. return self.conf_parser.sections()
  17. def get_options(self,section):
  18. return self.conf_parser.options(section)
  19. def get_items(self,section):
  20. return self.conf_parser.items(section)
  21. def get_val(self,section,option,is_bool = False,is_int = False):
  22. if is_bool and not is_int:
  23. #bool类型配置
  24. val = self.conf_parser.getboolean(section,option)
  25. return val
  26. elif not is_bool and is_int:
  27. val = self.conf_parser.getint(section,option)
  28. return val
  29. val = self.conf_parser.get(section,option)
  30. return val

配置文件格式如下

  1. [labels_of_search]
  2. base_dir = /home/lei.wang/datas/datas_user_label
  3. cheap = %(base_dir)s/cheap_all
  4. receptions = %(base_dir)s/receptions_all
  5. breakfast = %(base_dir)s/breakfast_all
  6. [result_file]
  7. result_file = /home/lei.wang/datas/datas_user_label/hive_data/user_labels
  8. 注意%(xxx)s的用法,xxx需要放在同一个section里