• configparser模块


    #配置文件的解析
     以下所述块相当于section
    # 这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows
    # INI文件的格式相同
    # 该模块的作用 就是使用模块中的RawConfigParser()ConfigParser() SafeConfigParser(),
    # 这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查操作


    # 读取配置文件
    # read(filenames) filesnames是一个列表,需要从文件加载初始值的应用程序应该在调用read()之前使用readfp()加载所需的文件或文件。
    # readfp(fp[, filename]) fp中,从文件或文件类对象中读取和解析配置数据(只使用readline()方法)。如果文件名被省略,并且fp有一个name属性,它被用于文件名;默认值为< ? >

    # 写入配置文件
    # write(fileobject) 将配置的表写入指定的文件对象。这个表可以由未来的read()调用解析。


    #配置文件的生成

    import configparser
    config = configparser.ConfigParser() #实例化,生成对象

    #1、为文件添加内容

    #方式1 config[section] ={object:value}
    config['DEFAULT'] = {'name':'alex','age':23,'gender':'male'} #添加默认块
    #
    #方式2
    config["STUDENT"] = {}
    config["STUDENT"]["name1"] = 'keili'
    config["STUDENT"]["age1"] = "17"
    config["STUDENT"]["gender1"] = "female"
    #
    #方式3
    config["TEACH"] = {}
    newtype = config["TEACH"]
    newtype["t1"] = 'English'
    newtype["t2"] = "China"
    #
    #2、sections() 返回可用的section的列表;默认section(即DEFAULT)不包括在列表中
    print(config.sections())

    #3、判断块是否在config(配置文件中)存在,存在则返回True,否则返回False
    print('TEACH' in config) #True
    print("ad" in config) #False

    #4、从文件中取值
    #方法1
    print(config["TEACH"]['t1']) #取出他t1的值,此处为t1=English
    print(config["DEFAULT"]["age"]) #23
    #方法2
    print(config.get("DEFAULT","gender")) #male
    print(config.get("DEFAULT","age")) #23
    print('----------end---------')

    #5、遍历键
    #方法1
    for key in config["DEFAULT"]:
    print(key)
    #方法2
    print(config.options("STUDENT")) #options() 返回指定块中的键,包括默认的DEFAULT

    #6、增加
    #增加块add_section(section)
    config.add_section('AAA')
    #增加键值对set(section, key, value)
    config.set("AAA","a1","fdd")

    #7、items() 返回给定section中每个选项的(object,value)对的列表
    print(config.items("AAA")) #[('name', 'alex'), ('age', '23'), ('gender', 'male'), ('a1', 'fdd')]

    #8、删除
    #remove_option(section, option) 从指定的部分中删除指定的选项
    #remove_section(section) 从配置中删除指定的section
    #删除块
    config.remove_section("AAA")
    #删除键值对
    config.remove_option("TEACH","t1")

    #生成一个配置文件
    with open('example.ini','w') as config_file:
    config.write(config_file)
  • 相关阅读:
    神经网络-FPN 19
    机器学习
    神经网络-DenseNet 18
    神经网路骨架:各自的特点统计
    转载:一步一步制作根文件系统
    设计模式博客
    【转】PowerPC平台linux设备移植
    【收藏】自己动手写编译器、连接器
    查看pthread线程库中锁的持有者方法
    【转】深入 Linux 的进程优先级
  • 原文地址:https://www.cnblogs.com/shadowfolk/p/14673179.html
Copyright © 2020-2023  润新知