1.configparser模塊簡介
使用配置文件來靈活的配置一些參數是一件很常見的事情,配置文件的解析并不復雜,在python里更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是configParser
configParser解析的配置文件的格式比較象ini的配置文件格式,就是文件中由多個section構成,每個section下又有多個配置項
2.看一下configparser生成的配置文件的格式
ini配置文件格式如下:
這里是注釋
1
2
3
4
5
6
7
8
9
10
11
|
[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.讀取文件內容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
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' )) |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/hghua/p/13141711.html