用於生成和修改常見配置文檔,當前模塊的名稱在 python 3.x 版本中變動爲 configparser。python
來看一個好多軟件的常見文檔格式以下spa
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
python生成配置文件code
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile)
讀取配置文件信息server
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import configparser config = configparser.ConfigParser() config.sections() config.read('example') config.sections() for i in config.keys(): print(i, end=' ') print("=" * 50) print(config.keys()) print(config['bitbucket.org']['User']) print(config['DEFAULT']['Compression']) topsecret = config['topsecret.server.com'] print(topsecret['ForwardX11']) print(topsecret['Port']) for key in config['bitbucket.org']: print(key) print(config['bitbucket.org']['ForwardX11'])
configparser增刪改查語法blog
########### i.cfg file ########## [section1] k1 = v1 k2:v2 k5 : 10 [section2] k3 = v3 k4 = v4 age : 88 ################################# #!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: songwei import configparser # ########## 讀 ########## config = configparser.ConfigParser() config.read('example') secs = config.sections() print(secs) #--->['section1', 'section2'] options = config.options('section2') print(options) #--->['k3', 'k4', 'age'] item_list = config.items('section2') print(item_list) #--->[('k3', 'v3'), ('k4', 'v4'), , ('age', '88')] val = config.get("section1", "k2") print(val) #--->v2 val2 = config.getint('section1','k5') print(val2) #---> 10 # ########## 改寫 ########## config = configparser.ConfigParser() config.read('example') sec = config.remove_section('section1') #刪除 config.write(open('i.cfg', "w")) sec = config.has_section('wupeiqi') print(sec) sec = config.add_section('wupeiqi') print(sec) config.write(open('i.cfg', "w")) config.set('section2','k4',"11111") # config.defaults() config.write(open('i.cfg', "w")) # config.remove_option('section2','age') # config.write(open('i.cfg', "w"))