Python解析properties配置文件的方法与示例

阿橙
阿橙
发布时间:2026-10-12| 3人浏览过
原创

本文介绍在Python中加载和解析properties配置文件的方法,适用于深度学习等场景的全局参数管理。通过自定义PropertiesUtil工具类,读取global.properties文件并按层级解析键值对,实现便捷配置管理。

本文介绍一种在Python中加载并解析properties配置文件的方法,供读者参考。

具体实现参考了前文:https://www.jb51.net/article/137393.htm

通常在Java开发中会遇到解析properties文件的需求,而在Python中较少见。但在运行深度学习项目时,将部分参数统一放置在global.properties全局文件中,能显著提升使用便利性。其核心原理是加载文件内容,并通过逐行解析判断包含“=”符号的键值对。此处记录一个从网络获取的工具类实现。

工具类文件名为PropertiesUtil.py

# -*- coding:utf-8 -*-
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, 'Ur')
      for line in pro_file.readlines():
        line = line.strip().replace('\n', '')
        if line.find("#")!=-1:
          line=line[0:line.find('#')]
        if line.find('=') > 0:
          strs = line.split('=')
          strs[1]= line[len(strs[0])+1:]
          self.__getDict(strs[0].strip(),self.properties,strs[1].strip())
    except Exception, e:
      raise e
    else:
      pro_file.close()
    return self.properties

借助上述代码即可完成对properties文件的解析。接下来需要新建一个配置文件。

新建global.properties文件

a.name.last=jie
b.name.first=shi
#b.name=shijie

编写测试脚本test.py

from PropertiesUtil import Properties
dictProperties=Properties("global.properties").getProperties()
print dictProperties

控制台输出结果如下:

/usr/bin/python2.7 /home/tengxing/rude-carnie/test.py {'a': {'name': {'last': 'jie'}}, 'b': {'name': {'first': 'shi'}}} Process finished with exit code 0

该方法操作简便,尤其适用于深度学习场景。将模型路径、训练数据等参数集中存放在global.properties文件中,有助于提升配置管理的效率。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。