python之读取.ini文件操作

.ini必须满足以下格式(可多个)
[section]
option=value
option=value

[section]
option=value
option=value


.ini
读取:
ConfigParse类
1、引入  from configparse import Configparse
2、conf = Configparse()
3、读取.ini文件
   conf.read(fs,encoding="utf-8")
4、通过get方法,获取section下的option的值。
   value = .get(section,option) # 字符串
   
   boolean: getboolean() # 布尔值
   int:getint()   # 整数
   float:getfloat()  # 符点数

# 举例如下
from configparser import ConfigParser
class HandleConfig(ConfigParser):

    def __init__(self,file_path):
        super().__init__()
        self.read(file_path, encoding="utf-8")
conf = HandleConfig(file_path)

===================================================================================
.yaml
  字典、列表
  pyyaml
  import yaml
  1、打开文件 open
  2、加载文件数据为字典对象/列表对象
  yaml.load(fs,loader=yaml.FullLoader)

=========================================================================

# 应用
import logging
from class_config.handle_config import conf

class MyLogger(logging.Logger):

    def __init__(self,file=None):
        # 设置输出级别、输出渠道、输出日志格式
        # super().__init__(name,level)
        super().__init__(conf.get("log","name"),conf.get("log","level"))

        # 日志格式
        fmt = '%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d line:%(message)s'
        formatter = logging.Formatter(fmt)

        # 控制台渠道
        handle1 = logging.StreamHandler()
        handle1.setFormatter(formatter)
        self.addHandler(handle1)

        if file:
            # 文件渠道
            handle2 = logging.FileHandler(file,encoding="utf-8")
            handle2.setFormatter(formatter)
            self.addHandler(handle2)


# 是否需要写入文件
if conf.getboolean("log","file_ok"):
    file_name = conf.get("log","file_name")
else:
    file_name = None

# logger = MyLogger(conf.get("log","name"),conf.get("log","level"),file_name)
logger = MyLogger(file_name)

# 把file_ok=False改成True执行完对应的路径下会生成一个文件
logger.info("1111111111111111")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值