• 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()
    菜鸟的自白
  • 相关阅读:
    Oracle EBS Form调用JavaBean前期配置
    Oracle EBS Form Builder使用Java beans创建窗体
    将 Oracle Forms 集成到 Oracle ADF Faces 中
    Oracle EBS开发习惯
    支持MOAC功能的Form开发步骤
    Form的Trigger的优先级
    所有标准API
    EBS中Java并发程序笔记(1)
    ORACLE FORM中,如何使用警告?
    .Net Core3.0 WebApi 六: Sqlsugar+异步泛型仓储
  • 原文地址:https://www.cnblogs.com/lzjloveit/p/13966581.html
Copyright © 2020-2023  润新知