zoukankan      html  css  js  c++  java
  • python读写ini文件

    python来读写ini的配置文件

    读取文件:

    import configparser
    cfp = configparser.ConfigParser()
    cfp.read("test.ini")
    
    '''获取所有的selections'''
    selections = cfp.sections()
    print(selections) #  ['Title1', 'Title2']
    
    '''获取指定selections下的所有options'''
    options = cfp.options("Title1")
    print(options)  # ['key1', 'key2']
    
    '''获取指定selection下的指定option的值'''
    value= cfp.get("Title1", "key1")
    print(value)  # 1111111111
    
    '''判断是否含有指定selection 或 option'''
    print(cfp.has_section("Title1"))  # True
    print(cfp.has_option("Title1", "key3"))  # False

    写文件:

    import configparser
    cfp = configparser.ConfigParser()
    cfp.read("test.ini")
    
    cfp.add_section("Title3")  # 设置option的值
    cfp.set("Title3", "key1", "1111111111")  # 注意这里的selection一定要先存在!
    cfp.set("Title3", "key2", "2222222222")
    
    cfp.remove_section("Title3")  # 移除指定selection
    
    cfp.remove_option("Title2", "key1")  # 移除指定selection下的option
    
    with open("test.ini", "w+") as f:
        cfp.write(f)
  • 相关阅读:
    在c#中用指针操作图片像素点
    获取exe目录
    MySQL数据库之安装
    简介、变量、常数、if、基础数据类型、注释、input()
    day 1 预习
    Typora基础
    内存流
    System.in流
    Java IO 操作
    字节流、字符流
  • 原文地址:https://www.cnblogs.com/answerThe/p/11603958.html
Copyright © 2011-2022 走看看