python - configparser 配置文件
 

配置文件

[group1] # 支持的两种分隔符“=”, “:”
k1 = v1
k2:v2

[group2]
k1 = v1
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

configparser

import  configparser

config = configparser.ConfigParser()
config.read('i.cfg')

# ########## 读 ##########
secs = config.sections()
print(secs)
options = config.options('group2') # 获取指定section的keys
print(options)

#item_list = config.items('group2') # 获取指定 section 的 keys & values ,key value 以元组的形式
#print(item_list)

#val = config.get('group1','key') # 获取指定的key 的value
#val = config.getint('group1','key')

# ########## 改写 ##########
#sec = config.remove_section('group1') # 删除section 并返回状态(true, false)
#config.write(open('i.cfg', "w")) # 对应的删除操作要写入文件才会生效

#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w")) #


#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))

#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))

import configparser # 导入模块
config = configparser.ConfigParser()  #实例化(生成对象)
#config.sections()  #调用sections方法
conf = config.read('test.conf')  # 读配置文件(注意文件路径)

print(conf)


print(config.sections() )

a = 'bitbucket.org' in config #判断元素是否在sections列表内
print(a)
b = 'bytebong.com' in config
print(b)


print( config['bitbucket.org']['User'] ) # 通过字典的形式取值

"""
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
"""

文章作者: 以谁为师
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源!
              
  目录