(十八)configparser模块
2024-08-23 06:12:48
configparser模块一般是用来处理配置文件的,如:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no
如果想用python生成一个这样的配置文件怎么做?
把配置文件当做一个类似字典的对象去处理,即处理键值对
import configparser
config = configparser.ConfigParser() #拿到config对象 config["DEFAULT"] = {'ServerAliveInterval': '45', #第一个[DEFAULT]块,像字典一样去定义;[DEFAULT]块是默认的块,有特殊之处,见后面
'Compression': 'yes',
'CompressionLevel': '9'} config['bitbucket.org'] = {} #第二个[bitbucket.org]块
config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {'Port':'50022', #第三个[topsecret.server.com]块
'ForwardX11':'no'} with open('test.ini', 'w') as configfile: #自定义写入的文件
config.write(configfile)
查看
import configparser
config = configparser.ConfigParser() config.read('test.ini') #读取文件 print(config.sections()) #['bitbucket.org', 'topsecret.server.com'] #sections()就是所有的块,不包括DEFAULT默认块 print('bytebong.com' in config)# False #不存在就是false print(config['bitbucket.org']['User']) # hg #存在,拿到键user对应的值hg print(config['DEFAULT']['Compression']) #yes #存在,拿到键compression对应的值yes for key in config['bitbucket.org']: #user serveraliveinterval compression compressionlevel #除了user,还拿到了DEFAULT默认块里的键
print(key)
结果:
['bitbucket.org', 'topsecret.server.com']
False
hg
yes
user
serveraliveinterval
compression
compressionlevel
查看还有三个方法:
print(config.options('bitbucket.org')) #options()拿到键,同样包括默认块
#['user', 'serveraliveinterval', 'compression', 'compressionlevel']
print(config.items('bitbucket.org')) #items()拿到键值对,同样包括默认块
#[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('user', 'hg')]
print(config.get('bitbucket.org','compression')) #get()拿到一个块中的一个键对应的值
#yes
所以DEFAULT块是默认块,其他的每一个块中都包括默认块中的键值对
增删改
config.add_section('yuan') #新增yuan块
config.remove_section('topsecret.server.com') #删除topsecret.server.com块
config.set('bitbucket.org','user','admin') #修改bitbucket.org块的user键对应的值为admin
config.set('bitbucket.org','passwd','123456') #新增bitbucket.org块的passwd键,值为123456
config.remove_option('bitbucket.org','user') #删除bitbucket.org块的user键值对
config.set('yuan','k1','11111') #新增yuan块的k1键,值为11111 config.write(open('test123.ini', "w")) #最后要写入文件,可以是读取时的文件(即覆盖),也可以是新增的另一个文件
最后被修改后的test123.ini文件:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9 [bitbucket.org]
passwd = 123456 [yuan]
k1 = 11111
最新文章
- MCMC 、抽样算法与软件实现
- HTML5特性速记图
- Android工具与其它
- 格式太旧或是类型库无效。 (Exception from HRESULT: 0x80028019 (TYPE_E_UNSUPFORMAT))
- 专门讲讲这个MYSQL授权当中的with grant option的作用
- Core Data入门-备用
- 4个常用的HTTP安全头部
- sql语句:CASE WHEN END 的用法
- Android安卓身份证识别SDK
- JavaWeb 后端 <;七>; 之 mvc3层架构
- Fitnesse - Slim Tables
- 异常处理-try catch
- 微信支付 chooseWXPay:fail
- MYSQL 优化器 源码解析
- 时间序列(六): 炙手可热的RNN: LSTM
- Oracle查询今天、昨天、本周、上周、本月、上月数据
- vs未能解析此远程名称: &#39;api.nuget.org&#39;
- 此文记录了我从研二下学期到研三上学期的找工历程,包括百度、腾讯、网易、移动、电信、华为、中兴、IBM八家企业的面试总结和心得--转
- php模拟http请求
- iOS面试题--网络--如何处理多个网络请求的并发的情况