python的configparser使用實例

1 生成配置文件

conf = configparser.ConfigParser()
conf["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }

conf['bitbucket.org'] = {'User':'hg'}
conf['topsecret.server.com'] = {
    'Host Port':'50022',
    'ForwardX11':'no'
}
with open('example.ini', 'w') as configfile:
    conf.write(configfile)

2 讀取或修改配置文件

2.1 查找

# 查找
import configparser
conf = configparser.ConfigParser()
# 基於字典的形式,查找文件內容
# 讀取section
print(conf.sections())  # [] 讀取前爲空
conf.read('example.ini')
# print(conf.sections())  # ['bitbucket.org', 'topsecret.server.com']

# 查找section,基於字典形式判斷
print('bytebong.com' in conf)  # False
print('bitbucket.org' in conf)  # True

# 取值 section中選項的值:
print(conf['bitbucket.org']["user"])  # hg
print(conf['DEFAULT']['Compression'])  # yes
print(conf['topsecret.server.com']['ForwardX11'])  # no
print(conf['bitbucket.org'])  # <Section: bitbucket.org>
# 取鍵方式1:遍歷
for key in conf['bitbucket.org']:  # 注意,有default會默認default的鍵
    print(key)
# 取鍵方式2:
print(conf.options('bitbucket.org')) #取出section下所有的鍵,返回列表
print(conf.items('bitbucket.org'))  # 取出setciont下所有的鍵值對,返回元組列表。
print(conf.get('bitbucket.org', 'compression'))  # get方法:取出Section下的key對應的value

2.2 增刪改

# 增刪改
import configparser
config = configparser.ConfigParser()
config.read('example.ini') # 讀取文件
# section增刪操作
config.add_section('yuan') #
config.remove_section('bitbucket.org') #刪除section

# section中選項的增刪改
# 增
config.set('yuan', 'k4', '323') #set之前,必須要有section,沒有就要先增加add_section,否則會報錯
# 刪
config.remove_option('topsecret.server.com', "forwardx11")
# 改
config.set('topsecret.server.com', 'host port', '2223')
# 寫入
config.write(open('new2.ini', "w")) #寫入文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章