• python读取配置文件


    使用configparser模块读取配置文件

    读取.ini文件

    abc.ini

    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    
    [com.net]
    user = knight
    
    [ip,yeyese.clu]
    port = 1010
    forwardx11 = no

    读取操作

    from configparser import ConfigParser
    
    
    cfgg = ConfigParser()
    
    s = cfgg.read('abc.ini')
    
    print(s)
    # 读取配置文件的每个节段
    m = cfgg.sections()
    print(m)
    # 返回字符串
    p = cfgg.get('com.net','User')
    print(p)
    # 返回boolean 值
    n = cfgg.getboolean('DEFAULT','Compression')
    print(n)
    # 返回整型
    port = cfgg.getint('ip,yeyese.clu','Port')
    print(port)

    修改

    from configparser import ConfigParser
    
    cfg = ConfigParser()
    
    cfg.read('abc.ini')
    
    cfg.set('ip,yeyese.clu','Port','1010')
    
    
    with open('abc.ini','w') as f:
        cfg.write(f)

    添加

    from configparser import ConfigParser
    
    cfg = ConfigParser()
    
    cfg.read('abc.ini')
    
    cfg.add_section('user')
    cfg.set('user','lzj','123')
    cfg.set('user','hu','123')
    cfg.set('user','xing','123')
    cfg.set('user','zhuo','123')
    
    
    with open('abc.ini','w') as f:
        cfg.write(f)

    创建配置文件

    from configparser import ConfigParser
    
    cfg = ConfigParser()
    
    cfg.read('ab.ini')
    
    cfg.add_section('user')
    cfg.set('user','lzj','123')
    cfg.set('user','hu','123')
    cfg.set('user','xing','123')
    cfg.set('user','zhuo','123')
    
    
    with open('ab.ini','w') as f:
        cfg.write(f)

     删除节段

    from configparser import ConfigParser
    
    cfg = ConfigParser()
    
    cfg.read('abc.ini')
    
    cfg.remove_section('user')
    
    
    
    with open('abc.ini','w') as f:
        cfg.write(f)

    使用pyyaml 模块读取yml文件

    import yaml
    import os
    
    
    # 获取当前脚本所在文件夹路径
    curPath = os.path.dirname(os.path.realpath(__file__))
    print(curPath)
    
    # 获取yaml文件夹路径
    yamlPath = os.path.join(curPath,'nb.yaml')
    
    from pathlib import Path
    mypath = Path(yamlPath)
    print(mypath)
    if not  mypath.exists():
        # windows创建文件命令
        os.popen("type nul>{}".format(yamlPath))
        import time
        time.sleep(1)
    print(yamlPath)
    
    f = open(yamlPath,'r',encoding='utf8')
    
    d = yaml.load(f,Loader=yaml.FullLoader) # **
    # Loader 如果不加这个参数,会出现警告
    print(d)
    
    
    print(d['nb']['user'])
    print(d['redis'])
    print(d['redis']['host'])
    
    f.close()
    菜鸟的自白
  • 相关阅读:
    分页实现
    jquery扩展提示框
    可拖拽可扩展面板
    单表查询结果转换成泛型集合
    压缩远程图片并返回
    windows下python安装架包的问题
    从网络上下载数据
    自己实现jquery
    如何利用拼音首字母查询数据库
    正则表达式
  • 原文地址:https://www.cnblogs.com/lzjloveit/p/13966581.html
Copyright © 2020-2023  润新知