创建配置文件
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9',
'ForwardX11': 'yes'
}
config['bitbucket.org'] = {'User': 'hg'}
config['topsecret.server.com'] = {'Host Port': '50022', 'ForwardX11': 'no'}
with open('example.ini', 'w') as configfile:
config.write(configfile)
生成的配置文件内容如下:
# example.ini:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host
port = 50022
forwardx11 = no
读取配置文件
import configparser
config = configparser.ConfigParser()
# ---------------------------查找文件内容,基于字典的形式
print(config.sections()) # []
config.read('example.ini')
print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
print(config['bitbucket.org']["user"]) # hg
print(config['DEFAULT']['Compression']) # yes
print(config['topsecret.server.com']['ForwardX11']) # no
print(config['bitbucket.org']) # <Section: bitbucket.org>
# 注意,有default会默认default的键
for key in config['bitbucket.org']:
print(key)
# user
# serveraliveinterval
# compression
# compressionlevel
# forwardx11
# 同for循环,找到'bitbucket.org'下所有键
print(
config.options('bitbucket.org')) # ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
# 找到'bitbucket.org'下所有键值对
print(config.items(
'bitbucket.org')) # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
# 获取Section下的key对应的value
print(config.get('bitbucket.org', 'compression')) # yes
对配置文件的修改
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')
config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com', "forwardx11")
config.set('topsecret.server.com', 'k1', '11111')
config.set('yuan', 'k2', '22222')
with open('new.ini', "w") as f:
config.write(f)
修改后的配置文件如下:
# example.ini:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022
forwardx11 = no
new.ini:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[topsecret.server.com]
host port = 50022
k1 = 11111
[yuan]
k2 = 22222
评论区