python configparser使用
.ini文件由若干section(部分)组成, 而每一个section又由若干键值对组成。
以 example.ini为例:
[DEFAULT]ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
创建.ini文件
import configparser# configd对象类似于字典
config = configparser.ConfigParser()
config["DEFAULT"] = {
"ServerAliveInterval" : 45,
"Comperssion": "yes",
"ComperssionLevel": 9,
"ForwardX11": "yes"
}
config["bitbucket.org"] = {}
config["bitbucket.org"]["user"] = "hg"
config["topsecret.server.com"] = {}
config["topsecret.server.com"]["Port"] = "50022"
config["topsecret.server.com"]["ForwardX11"] = "no"
with open("example.ini", "w") as fp:
# 写入文件
config.write(fp)
读取.ini文件
config = configparser.ConfigParser()config.read("example.ini")
关于section
import configparserconfig = configparser.ConfigParser()
config.read("example.ini")
# 获取section名称列表
print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
# 获取默认section名称
print(config.default_section) # DEFAULT
# 获取默认section对象
print(config.defaults()) # OrderedDict([('serveraliveinterval', '45'), ('comperssion', 'yes'), ('comperssionlevel', '9'), ('forwardx11', 'yes')])
# 判断是否包含对应的section
print('bitbucket.org' in config)
print(config.has_section("example.com"))
# 添加section的2种方式
config['example.com'] = {}
config['example.com']['username'] = 'python'
config.add_section("example.com1")
config.write(open("tmp.ini", "w"))
# 删除section的2种方式
del config['example.com']
config.remove_section("example.com")
config.write(open("tmp.ini", "w"))
关于option
import configparserconfig = configparser.ConfigParser()
config.read("example.ini")
# 这里的option于key对应
# 获取section对应的key列表
bitbucket_keys = config.options('bitbucket.org')
print(bitbucket_keys) # ['user', 'serveraliveinterval', 'comperssion', 'comperssionlevel', 'forwardx11']
# 判断section中是否存在对应的key
print(config.has_option("bitbucket.org", "User"))
print('user1' in config.options('bitbucket.org'))
print('user1' in config['bitbucket.org'])
# 添加option
config['bitbucket.org']['pwd'] = 'python'
config.write(open("tmp.ini", "w"))
# 删除option的2种方式
del config['bitbucket.org']['User']
config.remove_option("bitbucket.org", "User")
config.write(open("tmp.ini", "w"))
value相关
import configparserconfig = configparser.ConfigParser()
config.read("example.ini")
# 获取key对应的value的2种方式
user = config['bitbucket.org']['User']
user = config.get('bitbucket.org', 'User')
print(user) # hg
interval = config.getint("topsecret.server.com", "Port")
print(interval) # 45
compression = config.getboolean("topsecret.server.com", "ForwardX11")
print(compression)
# 还有 config.getfloat()
# 设置value的2种方式
config.set('bitbucket.org', 'User', 'peter')
config['bitbucket.org']["User"] = "peter"
config.write(open("tmp.ini", "w"))
以上是 python configparser使用 的全部内容, 来源链接: utcz.com/z/389410.html