configParse模块

一、配置文件简介

  在各种程序里面都有配置文件,为了对配置文件进行操作。 python中引入了configParse模块进行操作。

  配置数值类型:

    配置文件中,我们看到的bool型,整数型,在我们操作的时候,都是字符串类型。

  配置文件的三种定义:

      section:章节。 章节需要注意,大写的DEFAULT的基类,下面所有新增加的章节,都会继承这个,后面章节不写option都会继承这个章节的。

      option :选项,是每一个章节的定义。

      value:选项的值

 

二、配置文件模块的使用

2.1 初步认识使用方法

import configparser
import os
conf = configparser.ConfigParser()  # 第一步:生成一个configParser对象,所有的操作都是根据这个对象来的,

conf['DEFAULT'] = {}           # 第二步:先生产一个章节,必需先定义一个字典 (空字典,或 有值的字典 或 k,v的方式)
conf['DEFAULT']['base_dir'] = 'c:/Users/sothi/Desktop/py2018/02-auto/data'
conf['DEFAULT']['db_type'] = 'db'
conf['DEFAULT']['db_path'] = 'data.db'
conf['DEFAULT']['max_items'] = '1000'
conf['DEFAULT']['auto_save'] = 'True'

conf['louhui'] = {}
conf['louhui']['auto_del'] = 'True'

                     # 第三步:写入到文件中
base_dir = r'C:UsersLHDesktopdata'
path = os.path.join(base_dir, 'comeon.ini')
with open(path, 'w') as f:
    conf.write(f)  # 使用conf对象进行io

2.2 配置文件的读写

2.2.1 写入到配置文件

base_dir = r'C:UsersLHDesktopdata'
path = os.path.join(base_dir, 'comeon.ini')
with open(path, 'w') as f:
    conf.write(f)  # 使用conf对象进行io。 conf就是上面的对象

2.2.2 读取配置文件到内存中

base_dir = r'C:UsersLHDesktopdata'
path = os.path.join(base_dir, 'comeon.ini')

# 读取配置文件
conf = configparser.ConfigParser()  # 定义一个对象接收
conf.read(path)

三、各种方法大全

  配置文件的所有操作都是基于  configParse对象来操作。这点记住

 3.1 增加

  增加有两种方法:使用字典的形式来操作  或 使用内置方法

# 1.用前面写的方式追加
conf['diaosinan'] = {}
conf['diaosinan']['auto_add'] = '1'
with open(path, 'w') as f:
    conf.write(f)

# 2.使用add_section进行追加,使用set使用set进行各种修改
conf.add_section('diaosinan')
conf.set('diaosinan','auto_dellll', '1')   # set可以进行修改,也可以添加
conf.set('DEFAULT', 'auto_save', 'False')  # 修改父类的val
print(conf['louhui']['auto_save'])         # 子类直接改变

3.2 删除

  •   self.conf.remove_option()
  •        self.conf.remove_section()

def delete_option(self, section, option):
        '删除指定的section下的option'
        if self.conf.has_section(section) and self.conf.has_option(section, option):
            self.conf.remove_option(section, option)
        else:
            print('section or option is wrong!')

3.3 修改

  直接使用3.1中的set可以进行修改。

3.4 查看

查看的各种方法

conf.has_section()      # 查看是否有该章节
conf.has_option()       # 查看是否有该option

conf.sections()         # 返回所有的章节.默认的大写的DEFAULT是不返回的,DEFAULT是默认的基类,类似继承,下面所有的都会继承这个属性
conf.options(section)   # 查看section下的所有章节

conf.items()            # 打印所有的项目

配置文件中获取的val是字符串,进行类型转换

# 获取指定的值
result = conf['louhui']['auto_save'] # 定义louhui这个章节的时候,没有auto_save,但是我们能打印出来,继承了DEFAULT
print(result, type(result))          # 返回的默认就是字符串. 我们可以用两种方式 进行 转换
print(conf.options('louhui'))
# 方式1
bool(result)

# 方式2
y = conf.getboolean('louhui','auto_save')
print(y, type(y))
##
louhui = conf['louhui']  # 定义一个变量名,存这个章节的对象
y = louhui.getboolean('auto_save')

s使用字典的方式进行操作

louhui = conf['louhui']
print(louhui['auto_save'])
print(louhui.get('auto_save'))

打印整个配置文件

# 打印整个配置文件
for k,v in conf.items():
    print(f'{[k]}')
    for key, val in conf.items(k):
        print(key, val)
    print('')

3.5 替换变量:

  替换变量:

import configparser,os
base_dir = r'C:UsersLHDesktopdata'
path = os.path.join(base_dir, 'louhui.lh')
# conf = configparser.ConfigParser()
conf = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
conf.read(path)
print(conf['de8ug']['db_path'])

四、自己封装的一个config类:

 1 import configparser,os
 2 
 3 
 4 class MyConf:
 5     def __init__(self, path: str):
 6         '初始化的时候读取配置文件'
 7         self.path = path
 8         self.conf = configparser.ConfigParser()
 9         self.conf.read(self.path)  # 空文件也不会出错
10 
11     def add(self, section):
12         '增加一个章节'
13         if self.conf.has_section(section):
14             print('改章节已经存在')
15         else:
16             self.conf.add_section(section)
17 
18     def write(self, dic: dict):
19         '直接写入一个字典'
20         for k, v in dic.items():
21             self.conf[k] = v
22 
23     def del_section(self, section):
24         '删除section'
25         if self.conf.has_section(section):
26             self.conf.remove_section(section)
27         else:
28             print('该章节不存在')
29 
30     def modify_val(self, section, option, val):
31         if self.conf.has_section(section) and self.conf.has_option(section, option):
32             self.conf.set(section, option, val)
33             print('修改成功')
34         else:
35             print('修改失败')
36 
37     def delete_option(self, section, option):
38         '删除指定的section下的option'
39         if self.conf.has_section(section) and self.conf.has_option(section, option):
40             self.conf.remove_option(section, option)
41         else:
42             print('section or option is wrong!')
43 
44     def save(self):
45         '保存到配置文件中'
46         with open(self.path, 'w') as f:
47             self.conf.write(f)
48 
49     def check_all(self):
50         '答应全部'
51         for k, v in self.conf.items():
52             print(f'[{k}]')
53             for key, val in self.conf.items(k):
54                 print(key, val)
55         self.conf.remove_option()
56         self.conf.remove_section()
57 
58     def test(self, li):
59         print(self.conf.options(li))
60         x = self.conf['louhui']
61         print(type(x))
62 
63 
64 def main():
65     data = {
66         'DEFAULT': {
67             'base_dir': 'c:/Users/sothi/Desktop/py2018/02-auto/data',
68             'db_type': 'db'
69         },
70         'de8ug': {
71             'base_dir': 'c:/Users/sothi/Desktop/py2018/02-auto/data',
72             'db_type': 'pkl'
73         }
74     }
75 
76     data.get('lh', False)
77     base_dir = r'C:UsersLHDesktopdata'
78     path = os.path.join(base_dir, 'comeon123.ini')
79     myconf = MyConf(path)
80     myconf.write(data)
81 
82 
83 if __name__ == '__main__':
84     main()
封装的config

 

原文地址:https://www.cnblogs.com/louhui/p/9089444.html