当前位置: 移动技术网 > IT编程>脚本编程>Python > Python configparser模块封装及构造配置文件

Python configparser模块封装及构造配置文件

2020年08月08日  | 移动技术网IT编程  | 我要评论
1.configparser模块简介使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是configpa

1.configparser模块简介

使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是configparser

configparser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项

2.看一下configparser生成的配置文件的格式

ini配置文件格式如下:

这里是注释

[log]
log_path = base_dir/output/log/

[image]
img_path = base_dir/output/image/

[report]
report_path = base_dir/output/report/

[test_case]
test_case_path = base_dir/testdata/case.xlsx

3.读取文件内容

import configparser
import os
import sys

base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

if sys.platform == "win32":
  env_conf_dir = os.path.join(base_dir, 'common/conf/env_config.ini').replace('/', '\\')
else:
  env_conf_dir = os.path.join(base_dir, 'common/conf/env_config.ini')

class config(object):

  def __init__(self, path):
    self.path = path #配置文件名
    self.cf = configparser.configparser() #创建一个配置文件对象
    self.cf.read(self.path, encoding='utf-8') # 调用配置文件对象的读取方法,并传入一个配置文件名

  def get(self, field, key): # 获取字符串类型的选项值
    result = ""
    try:
      result = self.cf.get(field, key)
    except:
      result = ""
    return result

  def set(self, field, key, value):
    try:
      self.cf.set(field, key, value)
      self.cf.write(open(self.path, 'w'))#创建一个配置文件并将获取到的配置信息使用配置文件对象的写入方法进行写入
    except:
      return false
    return true

def r_config(config_file_path, field, key):
  rf = configparser.configparser()
  try:
    rf.read(config_file_path, encoding='utf-8')
    if sys.platform == "win32":
      result = rf.get(field, key).replace('base_dir', str(base_dir)).replace('/', '\\')
    else:
      result = rf.get(field, key).replace('base_dir', str(base_dir))
  except:
    sys.exit(1)
  return result
def w_config(config_file_path, field, key, value):
  wf = configparser.configparser()
  try:
    wf.read(config_file_path)
    wf.set(field, key, value)
    wf.write(open(config_file_path, 'w'))
  except:
    sys.exit(1)
  return true
if __name__ == '__main__':
  print(r_config(env_conf_dir, 'log', 'log_path'))
  print(r_config(env_conf_dir, 'db', 'database'))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网