zoukankan      html  css  js  c++  java
  • python3 之configparser 模块

    configparser 简介

    configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近
    [db]
    db_count = 3
    1 = passwd
    2 = data
    3 = ddf
    4 = haello

    “[ ]”包含的为 section,section 下面为类似于 key - value 的配置内容;
    configparser 默认支持 ‘=’ ‘:’ 两种分隔。

    import configparser
    import os
    def get_db():
         config=configparser.ConfigParser()     #调用配置操作句柄
         config_sec=config.sections()           #查看所有内容 现在还是[]
         print(config_sec)
         Filepath="/home/python/tmp/db.ini"
         if os.path.exists(Filepath):
             config.read(Filepath)              #python3 中要用read
             db_count=config.get("db","db_count")  #查看db下面db_count的值
             db_count=int(db_count)             #转化为数值
             print(db_count)
             print(config.items("db"))          #查看所有的值
             
             
    if __name__=='__main__':              #程序入口
        get_db()                            #执行函数
        
        
    >>> for i in config.items('db'):
    ...   print(i)
    ...
    ('db_count', '3')
    ('1', 'passwd')
    ('2', 'data')
    ('3', 'ddf')
    ('4', 'haello')    


    >>> config.get('db','1')
    'passwd'

    检查:
    >>> '1' in config['db']
    True
    >>> 'passwd' in config['db']
    False
    >>>
    添加:
    >>> config.add_section('Section_1')
    >>> config.set('Section_1', 'key_1', 'value_1')   # 注意键值是用set()方法
    >>> config.write(open('db.ini', 'w'))             # 一定要写入才生效
    删除:
    >>> config.remove_option('Section_1', 'key_1')
    True
    >>> config.remove_section('Section_1')
    True
    >>> config.clear()  # 清空除[DEFAULT]之外所有内容
    >>> config.write(open('db.ini', 'w'))


    import configparser
    import os
    def get_db():
         config=configparser.ConfigParser()
         config_sec=config.sections()
         print(config_sec)
         Filepath="/home/python/tmp/db.ini"
         if os.path.exists(Filepath):
             config.read(Filepath)
             db_count=config.get("db","db_count")
             db_count=int(db_count)
             print(db_count)
             print(config.items("db"))
             allrules=[]
             for a in range(1,db_count+1):
                 allrules.append(config.get("db",str(a)))
             print( allrules)
         else:
                   sys.exit(6)
    if __name__=='__main__':
            get_db()
            
    运行结果:
    []
    3
    [('db_count', '3'), ('1', 'passwd'), ('2', 'data'), ('3', 'ddf'), ('4', 'haello')]
    ['passwd', 'data', 'ddf']




  • 相关阅读:
    数据库一直显示恢复中。。记录一则处理数据库异常的解决方法
    MSSQl分布式查询
    ASP.NET MVC中实现数据库填充的下拉列表 .
    理解浮点数的储存规则
    获取 "斐波那契数列" 的函数
    Int64 与 Currency
    学 Win32 汇编[33] 探讨 Win32 汇编的模块化编程
    学 Win32 汇编[34] 宏汇编(1)
    Delphi 中 "位" 的使用(2) 集合
    如何用弹出窗口显示进度 回复 "嘿嘿嘿" 的问题
  • 原文地址:https://www.cnblogs.com/hello-wei/p/9768048.html
Copyright © 2011-2022 走看看