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)
  • 相关阅读:
    树莓派写Python程序输入不了#
    树莓派系统安装、HDMI显示
    网络七层协议
    TCP协议中的三次握手和四次挥手(图解)(转载http://blog.csdn.net/whuslei/article/details/6667471)
    英语积累
    读《淘宝技术这十年》--笔记
    关于imx6核心板qt系统U盘挂载
    《赢在测试2》-- 推荐的阅读书籍
    三月,关于团队管理的重要性
    自动化测试及工具的一点理解
  • 原文地址:https://www.cnblogs.com/ftl1012/p/9383326.html
Copyright © 2011-2022 走看看