python读取properties配置文件并解析

ld.properties

#配置信息
database.type=Argo
database.name=dd
database.ip=10.12.15.225
database.port=10000
database.username=user
database.password=passwd

properties_handler.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
脚本名称:properties_handler.py
脚本功能:解析.properties配置文件
编写人:  pangtaishi
编写日期:2021-02-28
'''

import os
import sys

class Properties(object):
  def __init__(self, fileName):
    self.fileName = fileName
    self.properties = {}

  def __getDict(self,strName,dictName,value):
    if(strName.find('.')>0):
      k = strName.split('.')[0]
      dictName.setdefault(k,{})
      return self.__getDict(strName[len(k)+1:],dictName[k],value)
    else:
      dictName[strName] = value
      return
      
  def getProperties(self):
    try:
      pro_file = open(self.fileName, 
Python 2 中,你可以使用 `ConfigParser` 类来解析 properties 配置文件,但是需要进行一些特定的设置。以下是一个示例: ```python from ConfigParser import ConfigParser class Properties(ConfigParser): def read(self, filenames): self._filenames = filenames return ConfigParser.read(self, filenames) def get(self, section, option): return ConfigParser.get(self, section, option) def items(self, section): return ConfigParser.items(self, section) properties = Properties() properties.read('config.properties') host = properties.get('database', 'host') port = properties.get('database', 'port') username = properties.get('database', 'username') password = properties.get('database', 'password') database = properties.get('database', 'database') ``` 在这个示例中,我们创建了一个名为 `Properties` 的子类,它继承自 `ConfigParser` 类。我们还重写了 `read`、`get` 和 `items` 方法来支持 properties 文件的解析。最后,我们创建了一个 `properties` 对象并使用 `read` 方法来读取配置文件,然后使用 `get` 方法获取配置项的值。 需要注意的是,在 properties 文件中,配置项和值之间需要用等号(=)分隔。每个配置项都应该在自己的行上,并且可以使用节头将它们分组。例如: ``` # Database configuration database.host = localhost database.port = 5432 database.username = myuser database.password = mypassword database.database = mydatabase ``` 在这个示例中,我们使用了 `database` 节头来将所有数据库配置项分组。你可以根据自己的需要自由组织你的配置文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大数据架构师Pony

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值