configparser模块是解析配置文件时使用的模块。 处理方式类似字典
配置文件内容:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
import configparser
conf = configparser.ConfigParser() # 创建个configparser对象
conf.read('conf.ini') # 读入文件
print(conf.sections())
print(conf.default_section)
print(conf['bitbucket.org']) # 取得bitbucket.org部分的数据
# print(list(conf['bitbucket.org'].keys())) # 处理方法类似于字典
# 遍历'bitbucket.org'的参数
for k,v in conf['bitbucket.org']: # 取得的数据不光有'bitbucket.org',同时也继承了DEFAULT的数据
print(k,v)
# 判断参数是否存在
if 'sss' in conf['bitbucket.org']:
pass
增删改查:
import configparser
conf = configparser.ConfigParser() # 创建个configparser对象
conf.read('conf.ini') # 读入文件
# 查
print(dir(conf))
print(conf.options('topsecret.server.com')) # 取topsecret.server.com得keys
print(conf['topsecret.server.com']['port']) # 取topsecret.server.com得port值
# 增
conf.add_section('www.com')
conf['www.com']['User'] = 'kaka' # 值必须是str。
conf.set('www.com','Age','22') # 也可以这样赋值
conf.write(open('test.ini','w')) # 修改完需要写入
# 删
conf.remove_option('www.com','User') # 删掉option
conf.write(open('test.ini','w')) # 修改完需要写入
conf.remove_section('www.com') # 删掉部分
conf.write(open('test.ini','w')) # 修改完需要写入