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)
  • 相关阅读:
    几个关于文本文件、字符串、编码的函数
    海量数据解决思路之Hash算法
    从头到尾彻底解析哈希表算法
    几个 GetHashCode 函数
    DELPHI指针的使用
    关于Delphi中的字符串的详细分析
    TStringList常用操作
    Pascal 排序算法
    Delphi THashedStringList用法
    Delphi代码创建形式规范 1.0
  • 原文地址:https://www.cnblogs.com/ftl1012/p/9383326.html
Copyright © 2011-2022 走看看