zoukankan      html  css  js  c++  java
  • python-读取配置文件

    一、基本的读取操作:

    • -read(filename)               直接读取文件内容
    • -sections()                      得到所有的section,并以列表的形式返回
    • -options(section)            得到该section的所有option
    • -items(section)                得到该section的所有键值对
    • -get(section,option)        得到section中option的值,返回为string类型
    • -getint(section,option)    得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数

    二、基本的写入操作:

    • -write(fp)  将config对象写入至某个 .init 格式的文件  Write an .ini-format representation of the configuration state.
    • -add_section(section)   添加一个新的section
    • -set( section, option, value)   对section中的option进行设置,需要调用write将内容写入配置文件
    • -remove_section(section)  删除某个 section
    • -remove_option(section, option) 

    三、代码示例

    1、新建一个配置文件:config.ini,内容如下:

    # 定义分组
    [DATABASE]
    host = xx.xx.xx.xx
    username = test
    password = ****
    port = 3306
    database = bi
    [LILY]
    name = lily
    age = 23
    [Xixi]
    name = lily

    2、在对配置文件进行读写操作前,我们需要先进行一个操作:

    import configparser
    config = configparser.ConfigParser()   # 实例化ConfigParser

    3、进行配置文件的读取操作。

    config.read("config.ini")   # 读取config.ini
    print(config.sections())
    value = config.get("DATABASE", "host")   # 读取 [DATABASE] 分组下的 host 的值
    print(value)

    4、进行配置文件的写入、删除操作。

    config.add_section("Haha")     # 创建一个组:Haha
    config.set("Haha", "name", "haha")   # 给Haha组添加一个属性name=haha
    config.remove_section('Xixi')   # 删除一个section
    config.remove_option('LILY',"name")  # 删除一个配置项
    # 写入 config.ini
    # r:读,r+:读写,w:写,w+:写读,a:追加,a+:追加读写
    # 写读和读写的区别:读写,文件已经存在;读写,创建新的文件
    #将文件内容读取到内存中,进过一系列操作之后必须写回文件,才能生效。写回文件的方式如下:(使用configparser的write方法)
    f = open('config1.ini', 'w') config.write(f) f.close()
  • 相关阅读:
    Windows 7 远程协助
    Windows 7 帮助和支持资源—第三方网站
    Windows 7 帮助和支持资源—第三方软件
    数据结构-队列
    数据结构-栈
    pycharm每日技巧-2
    数据结构-链表
    时间处理-1
    二维数组的排序
    《疯狂的简洁》书摘
  • 原文地址:https://www.cnblogs.com/peiya/p/12035366.html
Copyright © 2011-2022 走看看