zoukankan      html  css  js  c++  java
  • 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()
    菜鸟的自白
  • 相关阅读:
    .net发送邮件
    关于innerhtml的解释
    ASP.NET如何进行性能优化的问题,看一老兄的建议!【转】
    深入理解xLua热更新原理
    VS2010中的ListView的BUG
    asp,jsp,php等web开发必懂技术什么时候使用静态页,什么时候必须使用动态页
    IIS7虚拟目录出现HTTP错误500.19(由于权限不足而无法读取配置文件)的解决方案
    IIS错误信息另一个程序正在使用此文件,进程无法访问!
    CSS3图片展示效果
    一个简单的返回顶部效果
  • 原文地址:https://www.cnblogs.com/lzjloveit/p/13966581.html
Copyright © 2011-2022 走看看