本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

Python基础(24)之configparser模块

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:


创建配置文件

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

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×