侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

Python基础(24)之configparser模块

zze
zze
2019-05-28 / 0 评论 / 0 点赞 / 570 阅读 / 2878 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

创建配置文件

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
0

评论区