zoukankan      html  css  js  c++  java
  • python conf配置文件

    #为什么要做配置文件:
    #将所有的代码和配置都变成模块化可配置化,这样就提高了代码的重用性,不用都去修改代码内部,这个就是我们逐步
    #要做的事情,可配置化
    #configparser用法
    #1)创建configparser对象,并调用read()函数打开配置文件,里面填的参数是地址
    #2)配置文件的格式是[]包含的是section,section下有option=value这样的键值对
    '''


    3.依据section来读取相应的配置数据 读 写
    '''


    #1.创建configparser对象
    import configparser
    cf=configparser.ConfigParser()
    #2.从配置文件中读取数据
    import os
    cf.read(os.getcwd()+"/config.conf")
    #读取所有section
    print(cf.sections())       #返回列表形式    ['mysql_info', 'test_addSection']
    #读取section下的option
    print(cf.options(section="mysql_info"))  #只有key值 ['mysql_host', 'mysql_port', 'mysql_db', 'mysql_user', 'mysql_passwd']
    #读取键值对
    print(cf.items(section="mysql_info"))   #键值对 [('mysql_host', '120.76.42.189'), ('mysql_port', '3306'), ('mysql_db', 'future'), ('mysql_user', 'futurevistor'), ('mysql_passwd', '123456')]
    #读section里option
    print(cf.get("mysql_info","mysql_db"))     #future
    print(cf.getint("mysql_info","mysql_port")) #3306

    #写
    #添加option,修改也用set
    cf.set("mysql_info","type","mysql5.7")
    #添加section
    cf.add_section("test")
    cf.set("test","sex","female")
    #添加完option section后都要打开文件写入
    with open(os.getcwd()+"/config.conf","w") as cfile:
        cf.write(cfile)  #文件流写到文件中去

  • 相关阅读:
    面向对象深入:继承01——子类
    面向对象的基础知识——小结
    IP地址配置
    二、RPM包管理-rpm命令管理
    一、软件包管理简介
    关机重启命令
    网络命令
    权限管理命令
    字符截取命令
    shell-正则表达式(二)
  • 原文地址:https://www.cnblogs.com/nuonuozhou/p/8645210.html
Copyright © 2011-2022 走看看