zoukankan      html  css  js  c++  java
  • day6 ConfigParser模块 yaml模块

        yaml模块:

        python可以处理yaml文件,yaml文件安装的方法为:$ pip3 install pyyaml


       configparser模块,用来处理文件的模块,可以实现文件的增删改查

        configparser用于处理特定格式的文件,其本质上是利用open来操作文件

        下面来看看configarser模块的功能:  

    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    
    [bitbucket.org]
    user = hg
    
    [topsecret.server.com]
    host port = 50022
    forwardx11 = no

        上面代码格式就是configparser的常见格式,这中文件格式在有些地方很常见。

    import configparser
    
    config = configparser.ConfigParser()
    config["DEFAULT"] = {"ServerAliveInterval":"45",
                         "compression":"yes",
                         "CompressionLevel":"9"}
    
    config["bitbucket.org"] = {}
    config["bitbucket.org"]["user"] = "hg"
    config["topsecret.server.com"] = {}      #定义一个空的字典
    topsecret = config["topsecret.server.com"]   #把空的字典赋值给topsecret,生成一个空字典
    topsecret["Host Port"] = "50022"            #给字典添加键值对
    topsecret["Forwardx11"] = "no"
    config["DEFAULT"]["Forwardx11"] = "yes"
    with open("config_file.ini","w") as configfile:
        config.write(configfile)

    运行如下:
    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes

    [bitbucket.org]
    user = hg

    [topsecret.server.com]
    host port = 50022
    forwardx11 = no

        从上面代码可以看出,其文件的格式类似于字典的形式,包含keys和values类型,我们首先要定义一个configparser的文件,然后往文件中添加键值对。如上面代码所示:

        上面我们把字典写进文件之后,如何读取呢?下面来看看configparser.ConfigParser的文件操作:

        读取:

        >>> import configparser
      >>> config = configparser.ConfigParser()           #定义一个文件信息
      >>> config.sections()
      []

      >>> config.read('example.ini')
      ['example.ini']
       
        >>> config.sections()
        ['bitbucket.org', 'topsecret.server.com']
        下面来看看configparser模块中文件的增删改查:
    import configparser
    
    config = configparser.ConfigParser()
    config.read("config_file.ini")
    
    #删除文件中的字段
    sec = config.remove_section("bitbucket.org")
    config.write(open("config_file.ini","w"))
    
    #添加新的字段到文件中
    # sec = config.has_section("alex")
    # config.add_section("alex")
    # config["alex"]["age"] = "21"
    # config.write(open("config_file.ini","w"))
    
    
    #修改字段中的文件信息
    config.set("alex","age","28")
    config.write(open("config_file.ini","w"))

        上面代码的字段中,我们实现了增删改查的功能。要了解文件中的功能即可。并且能够操作,其实很多时候都对文件操作的思路都是相同的,只是实现的方式不一样,代码的写法不一样而已。

  • 相关阅读:
    update语句中存在''语法书写方式
    CSS的代码风格
    CSS的语法规范
    CSS层叠样式表导读
    CSS简介
    HTML基本标签(下)
    HTML基本标签(上)
    HTML简介导读
    集合及其运用
    字典的镶嵌
  • 原文地址:https://www.cnblogs.com/gengcx/p/6919043.html
Copyright © 2011-2022 走看看