天天看點

configparser子產品 --讀取配置檔案

說明:

configparser子產品是用來解析ini配置檔案的解析器,可以包含一個或多個節,每個節可以有多個參數(鍵=值)。

建立配置檔案:

import configparser  #配置檔案
config = configparser.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'


"""寫入字尾為.ini的檔案"""
with open('example.ini', 'w') as configfile:
    config.write(configfile)
           
configparser子產品 --讀取配置檔案

讀取配置檔案:

# [DEFAULT]為預設節點,後面的section都可以使用它的鍵值
import configparser  # 配置檔案

config = configparser.ConfigParser()
config.read("example.ini")

## 擷取所有節點
print(config.sections())  ## ['bitbucket.org', 'topsecret.server.com']

# 擷取預設節點的鍵值
print(
    config.defaults())  ## OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])

## 擷取預設節點的鍵
for item in config["DEFAULT"]:
    print(item)
	
## 擷取bitbucket.org的鍵,包含預設節點
print(config.options(
    "bitbucket.org"))  ## ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']

## 輸出元組,包括option的key和value
print(config.items(
    'bitbucket.org'))  ##[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

## 擷取bitbucket.org下user的值
print(config["bitbucket.org"]["user"])  ## hg
print(config.get("bitbucket.org", "user"))  ## hg

## 判斷bitbucket.org節點是否存在
print('bitbucket.org' in config)  ## True

## 擷取option值為數字的整數
print(config.getint("topsecret.server.com", "host port"))  ## 50022
           

删除配置檔案section和option的執行個體(預設分組有參數時無法删除,但可以先删除下面的option,再删分組):

import configparser  #配置檔案

config = configparser.ConfigParser()
config.read("example.ini")

"""删除分組"""
config.remove_section("bitbucket.org")
config.write(open('example.ini', "w"))

"""删除某組下面的某個值"""
config.remove_option("topsecret.server.com","host port")
config.write(open('example.ini', "w"))
           
上一篇: HTML