• Python3 中 configparser 使用注意事项


    在使用configparser时候应注意:

    ①配置文件(ini文件)的存放位置:配置文件和调用文件放在同一个文件包下面。

    使用read()函数读取并解析配置文件时,直接写配置文件(ini文件)的文件名即可。

    例如:

    cf=ConfigParser()                   #实例化
    cf.read("PageElementLocator.ini") #读取并解析配置文

    ②配置文件(ini文件)的存放位置:配置文件和调用文件未放在同一个文件包下面。

    使用read()函数读取并解析配置文件时,则需要写配置文件(ini文件)存放绝对路径。

    例如: 

    parentDirPath=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   #os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 获取当前文件所在目录的绝对路径 注意:该路径不包含当前目录
    path=parentDirPath+'\config\PageElementLocator.ini'      #获取配置文件的的绝对路径

    cf=ConfigParser()                   #实例化
    cf.read(path) #读取并解析配置文件

    未遵循上述两点,或者配置文件的路径写错,均会出现错误configparser.NoSectionError: No section

    ③items()此种方法获取到的配置文件中的options内容均被转换成小写。

    例如:test.ini 内容:

    [peizhi]
    A=Hello
    B=Word

             test.py 内容:

    from configparser import ConfigParser
    
    cf=ConfigParser()
    cf.read("test.ini")
    print(cf.items("peizhi"))
    

      执行结果:items获取配置文件中指定的section下的所有键值对。

    如果需要把items的返回结果以字典类型返回,那么需使用dict()方法。修改 test.py 内容:

    from configparser import ConfigParser
    
    cf=ConfigParser()
    cf.read("test.ini")
    print(dict(cf.items("peizhi")))

    再次执行,结果如下: 

     

              

  • 相关阅读:
    11.4 final类
    11.3 final方法
    【GIS】GIS坐标系
    【其他】短信轰炸
    【js】js传递对象
    【注解】Autowired
    【js】vue.js v-model
    【问题】ajax两种传递id值方式的区别
    【随笔】6.高筑墙 广积粮 缓称王
    【随笔】5.多恩亲王 Red Viper 奥伯伦之死。
  • 原文地址:https://www.cnblogs.com/benpao1314/p/9759096.html
Copyright © 2020-2023  润新知