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:\Users\LH\Desktop\data' 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:\Users\LH\Desktop\data' 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:\Users\LH\Desktop\data' 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:\Users\LH\Desktop\data' 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:\Users\LH\Desktop\data'
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

 

 

 


免責聲明!

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



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