python 模块之-configparser

python 模块configparser   配置文件模块

import configparser

  
config = configparser.ConfigParser()
config["DEFAULT"= {'ServerAliveInterval''45',
           'Compression''yes',
           'CompressionLevel''9'}
  
config['bitbucket.org'= {'User': 'hg'}
config['topsecret.server.com'= {'Host Port':'50022',
                  'ForwardX11','no'}
with open('example.ini''w') as configfile:       #把键值对写入 配置文件example.ini
   config.write(configfile)
 
结果:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no
 
config.read('example.ini')  # 关联文件才能操作里面键值
print(config.sections())   #['bitbucket.org', 'topsecret.server.com'] 查看段

print('bytebong.com' in config)# False 判断

print(config['bitbucket.org']['User']) # hg 查看值

print(config['DEFAULT']['Compression']) #yes 查看值

print(config['topsecret.server.com']['ForwardX11'])  #no 查看值
for key in config['bitbucket.org']:  #循环打印[bitbucker.org]的键
print(key)
###打印段[bitbucker.org]的所有键
print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
###循环打印段[bitbucker.org]的所有键值
print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

###打印段[bitbucket.org] 键compression 的值
print(config.get('bitbucket.org','compression'))#yes

config.add_section('yuan') #增加一个段 [yuan]
config.remove_section('topsecret.server.com')  # 删除一个段[topsecret.server.com]
config.remove_option('bitbucket.org','user')   # 删除这个[bitbucket.org]段里面的键和值User = hg
config.set('bitbucket.org','k1','11111')       # 添加[bitbucket.org]段里面 键值 k1 = 11111

config.write(open('i.cfg', "w")                # 写入的话 必须先执行这条命令  


上一篇:18.Llinux-触摸屏驱动(详解)【转】


下一篇:day 08 文件操作