Python解析properties配置文件的方法与示例
本文介绍在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程序设计有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









