zoukankan      html  css  js  c++  java
  • Python学习---重点模块之configparse

    configparse模块常用于生成和修改常见的配置文档

    生成配置模块:用字典写

    import configparser
    
    config = configparser.ConfigParser()
    config["DEFAULT"] = {'ServerAliveInterval': '45',
                         'Compression': 'yes',
                         'CompressionLevel': '9'}
    
    config['USER'] = {}
    config['USER']['User'] = 'hhh'
    config['SSH'] = {}
    topsecret = config['SSH']
    topsecret['Host Port'] = '50022'  # mutates the parser
    topsecret['ForwardX11'] = 'no'  # same here
    config['DEFAULT']['ForwardX11'] = 'yes'
    with open('example.ini', 'w') as configfile:
        config.write(configfile)

    image

    读取配置:config.sections()

    import configparser
    config = configparser.ConfigParser()
    config.read('example.ini')                  
    print(config.sections())                     # ['USER', 'SSH'], 默认不dayin[DEFAULT]模块
    print(config['USER'])                        # <Section: USER>
    print(config['USER']['user'])                # hg
    print(config.defaults())                     # 打印默认模块, 打印出来一个有序的字典
    print(config.has_section('USER'))            # True
     OrderedDict
    print(config['DEFAULT']['compressionlevel']) # 9   # 打印默认模块, 打印出来一个有序的字典OrderedDict
    # 跟字典一样,只打印key的信息
    for key in config['DEFAULT']:
        # print(key, v)  报错, too many values to unpack (expected 2)
        print(key)

    删除整个模块: remove,文件不能修改,只能覆盖,可以重新写入新的文件

    import configparser
    config = configparser.ConfigParser()
    config.read('example.ini')
    
    # 文件不能修改,只能覆盖,可以重新写入新的文件
    config.remove_section('SSH')
    with open('example.ini', 'w', encoding='utf-8') as f:
        config.write(f)
    print(config.sections())

    删除模块下的某个元素

    import configparser
    config = configparser.ConfigParser()
    config.read('example.ini')
    
    print(config.has_option('USER', 'user'))
    config.remove_option('USER', 'user')
    print(config.has_option('USER', 'user'))
    
    with open('example.ini', 'w', encoding='utf-8') as f:
        config.write(f)

    修改配置:

    import configparser
    config = configparser.ConfigParser()
    config.read('example.ini')
    
    print(config['USER']['user'])
    config.set('USER', 'user', 'ftl')
    print(config['USER']['user'])
    
    with open('example.ini', 'w', encoding='utf-8') as f:
        config.write(f)
  • 相关阅读:
    mysql通过data目录恢复数据库
    CentOS安装TortoiseSVN svn 客户端
    CentOS上安装Node.js
    PHP--进行模块化设计
    PHP开发绝对不能违背的安全铁则
    达内培训:php在线端口扫描器
    使用 PHP 限制下载速度
    使用无限生命期Session的方法
    使用php作linux自动执行脚本
    腾讯星座运势api
  • 原文地址:https://www.cnblogs.com/ftl1012/p/9383326.html
Copyright © 2011-2022 走看看