Python实现读取Properties配置文件的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现读取Properties配置文件的方法。分享给大家供大家参考,具体如下:

JAVA本身提供了对于Properties文件操作的类,项目中的很多配置信息都是放在了Properties文件。但是Python并没有提供操作Properties文件的库,所以,自己动手写个一个可以加载Properties文件的脚本。

class Properties:
  fileName = ''
  def __init__(self, fileName):
    self.fileName = fileName
  def getProperties(self):
  try:
  pro_file = open(self.fileName, 'r')
    properties = {}
    for line in pro_file:
      if line.find('=') > 0:
        strs = line.replace('\n', '').split('=')
        properties[strs[0]] = strs[1]
  except Exception, e:
  raise e
  else:
  pro_file.close()
    return properties

实际调用:

fileName = sys.path[0] + '\\'+ 'system.properties'
p = Properties(fileName)
properties = p.getProperties()
print properties[Key]

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

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

相关文章

Python判断字符串是否为字母或者数字(浮点数)的多种方法

str为字符串s为字符串 str.isalnum() 所有字符都是数字或者字母 str.isalpha() 所有字符都是字母 str.isdigit() 所有字符都是数字 str.iss...

Pyramid将models.py文件的内容分布到多个文件的方法

我们通过下面的文件结构,将models.py改成一个package. 复制代码 代码如下:myapp    __init__.py  &...

Pytorch 之修改Tensor部分值方式

一:背景引入 对于一张图片,怎样修改局部像素值? 二:利用Tensor方法 比如输入全零tensor,可认为为黑色图片 >>> n=torch.FloatT...

Python的print用法示例

Python 2.6中print不是函数,而是一个关键字,使用方式如下:复制代码 代码如下:print 1, 2  print 'a', 'b'  显示结果如下,用逗...

Python在Windows和在Linux下调用动态链接库的教程

Python在Windows和在Linux下调用动态链接库的教程

Linux系统下调用动态库(.so) 1、linuxany.c代码如下: #include "stdio.h" void display(char* msg){ p...