首页 > 其他 > 详细

ConfigParser模块

时间:2019-07-04 15:50:24      阅读:109      评论:0      收藏:0      [点我收藏+]

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

来看一个好多软件的常见文档格式如下

 1 [DEFAULT]
 2 ServerAliveInterval = 45
 3 Compression = yes
 4 CompressionLevel = 9
 5 ForwardX11 = yes
 6  
 7 [bitbucket.org]
 8 User = hg
 9  
10 [topsecret.server.com]
11 Port = 50022
12 ForwardX11 = no

python生成这样的文档

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)

读出(命令行)

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read(example.ini)
[example.ini]
>>> config.sections()
[bitbucket.org, topsecret.server.com]
>>> bitbucket.org in config
True
>>> bytebong.com in config
False
>>> config[bitbucket.org][User]
hg
>>> config[DEFAULT][Compression]
yes
>>> topsecret = config[topsecret.server.com]
>>> topsecret[ForwardX11]
no
>>> topsecret[Port]
50022
>>> for key in config[bitbucket.org]: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config[bitbucket.org][ForwardX11]
yes

增删改查

[section1]
k1 = v1
k2:v2
  
[section2]
k1 = v1
 
import ConfigParser
  
config = ConfigParser.ConfigParser()
config.read(i.cfg)
  
# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options(‘group2‘)
#print options
  
#item_list = config.items(‘group2‘)
#print item_list
  
#val = config.get(‘group1‘,‘key‘)
#val = config.getint(‘group1‘,‘key‘)
  
# ########## 改写 ##########
#sec = config.remove_section(‘group1‘)
#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"))

 

 

ConfigParser模块

原文:https://www.cnblogs.com/Desire1998/p/11132829.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!