在python中修改.properties文件的操作

在java 编程中,很多配置文件用键值对的方式存储在 properties 文件中,可以读取,修改。而且在java 中有 java.util.Properties 这个类,可以很方便的处理properties 文件, 在python 中虽然也有读取配置文件的类ConfigParser, 但如果习惯java 编程的人估计更喜欢下面这个用python 实现的读取 properties 文件的类:

"""
A Python replacement for java.util.Properties class
This is modelled as closely as possible to the Java original.
"""

import sys,os
import re
import time

class IllegalArgumentException(Exception):

  def __init__(self, lineno, msg):
    self.lineno = lineno
    self.msg = msg

  def __str__(self):
    s='Exception at line number %d => %s' % (self.lineno, self.msg)
    return s

class Properties(object):
  """ A Python replacement for java.util.Properties """

  def __init__(self, props=None):

    # Note: We don't take a default properties object
    # as argument yet

    # Dictionary of properties.
    self._props = {}
    # Dictionary of properties with 'pristine' keys
    # This is used for dumping the properties to a file
    # using the 'store' method
    self._origprops = {}

    # Dictionary mapping keys from property
    # dictionary to pristine dictionary
    self._keymap = {}

    self.othercharre = re.compile(r'(?<!\\)(\s*\=)|(?<!\\)(\s*\:)')
    self.othercharre2 = re.compile(r'(\s*\=)|(\s*\:)')
    self.bspacere = re.compile(r'\\(?!\s$)')

  def __str__(self):
    s='{'
    for key,value in self._props.items():
      s = ''.join((s,key,'=',value,', '))

    s=''.join((s[:-2],'}'))
    return s

  def __parse(self, lines):
    """ Parse a list of lines and create
    an internal property dictionary """

    # Every line in the file must consist of either a comment
    # or a key-value pair. A key-value pair is a line consisting
    # of a key which is a combination of non-white space characters
    # The separator character between key-value pairs is a '=',
    # ':' or a whitespace character not including the newline.
    # If the '=' or ':' characters are found, in the line, even
    # keys containing whitespace chars are allowed.

    # A line with only a key according to the rules above is also
    # fine. In such case, the value is considered as the empty string.
    # In order to include characters '=' or ':' in a key or value,
    # they have to be properly escaped using the backslash character.

    # Some examples of valid key-value pairs:
    #
    # key   value
    # key=value
    # key:value
    # key   value1,value2,value3
    # key   value1,value2,value3 \
    #     value4, value5
    # key
    # This key= this value
    # key = value1 value2 value3

    # Any line that starts with a '#' is considerered a comment
    # and skipped. Also any trailing or preceding whitespaces
    # are removed from the key/value.

    # This is a line parser. It parses the
    # contents like by line.

    lineno=0
    i = iter(lines)

    for line in i:
      lineno += 1
      line = line.strip()
      # Skip null lines
      if not line: continue
      # Skip lines which are comments
      if line[0] == '#': continue
      # Some flags
      escaped=False
      # Position of first separation char
      sepidx = -1
      # A flag for performing wspace re check
      flag = 0
      # Check for valid space separation
      # First obtain the max index to which we
      # can search.
      m = self.othercharre.search(line)
      if m:
        first, last = m.span()
        start, end = 0, first
        flag = 1
        wspacere = re.compile(r'(?<![\\\=\:])(\s)')
      else:
        if self.othercharre2.search(line):
          # Check if either '=' or ':' is present
          # in the line. If they are then it means
          # they are preceded by a backslash.

          # This means, we need to modify the
          # wspacere a bit, not to look for
          # : or = characters.
          wspacere = re.compile(r'(?<![\\])(\s)')
        start, end = 0, len(line)

      m2 = wspacere.search(line, start, end)
      if m2:
        # print 'Space match=>',line
        # Means we need to split by space.
        first, last = m2.span()
        sepidx = first
      elif m:
        # print 'Other match=>',line
        # No matching wspace char found, need
        # to split by either '=' or ':'
        first, last = m.span()
        sepidx = last - 1
        # print line[sepidx]

      # If the last character is a backslash
      # it has to be preceded by a space in which
      # case the next line is read as part of the
      # same property
      while line[-1] == '\\':
        # Read next line
        nextline = i.next()
        nextline = nextline.strip()
        lineno += 1
        # This line will become part of the value
        line = line[:-1] + nextline

      # Now split to key,value according to separation char
      if sepidx != -1:
        key, value = line[:sepidx], line[sepidx+1:]
      else:
        key,value = line,''

      self.processPair(key, value)

  def processPair(self, key, value):
    """ Process a (key, value) pair """

    oldkey = key
    oldvalue = value

    # Create key intelligently
    keyparts = self.bspacere.split(key)
    # print keyparts

    strippable = False
    lastpart = keyparts[-1]

    if lastpart.find('\\ ') != -1:
      keyparts[-1] = lastpart.replace('\\','')

    # If no backspace is found at the end, but empty
    # space is found, strip it
    elif lastpart and lastpart[-1] == ' ':
      strippable = True

    key = ''.join(keyparts)
    if strippable:
      key = key.strip()
      oldkey = oldkey.strip()

    oldvalue = self.unescape(oldvalue)
    value = self.unescape(value)

    self._props[key] = value.strip()

    # Check if an entry exists in pristine keys
    if self._keymap.has_key(key):
      oldkey = self._keymap.get(key)
      self._origprops[oldkey] = oldvalue.strip()
    else:
      self._origprops[oldkey] = oldvalue.strip()
      # Store entry in keymap
      self._keymap[key] = oldkey

  def escape(self, value):

    # Java escapes the '=' and ':' in the value
    # string with backslashes in the store method.
    # So let us do the same.
    newvalue = value.replace(':','\:')
    newvalue = newvalue.replace('=','\=')

    return newvalue

  def unescape(self, value):

    # Reverse of escape
    newvalue = value.replace('\:',':')
    newvalue = newvalue.replace('\=','=')

    return newvalue  

  def load(self, stream):
    """ Load properties from an open file stream """

    # For the time being only accept file input streams
    if type(stream) is not file:
      raise TypeError,'Argument should be a file object!'
    # Check for the opened mode
    if stream.mode != 'r':
      raise ValueError,'Stream should be opened in read-only mode!'

    try:
      lines = stream.readlines()
      self.__parse(lines)
    except IOError, e:
      raise

  def getProperty(self, key):
    """ Return a property for the given key """

    return self._props.get(key,'')

  def setProperty(self, key, value):
    """ Set the property for the given key """

    if type(key) is str and type(value) is str:
      self.processPair(key, value)
    else:
      raise TypeError,'both key and value should be strings!'

  def propertyNames(self):
    """ Return an iterator over all the keys of the property
    dictionary, i.e the names of the properties """

    return self._props.keys()

  def list(self, out=sys.stdout):
    """ Prints a listing of the properties to the
    stream 'out' which defaults to the standard output """

    out.write('-- listing properties --\n')
    for key,value in self._props.items():
      out.write(''.join((key,'=',value,'\n')))

  def store(self, out, header=""):
    """ Write the properties list to the stream 'out' along
    with the optional 'header' """

    if out.mode[0] != 'w':
      raise ValueError,'Steam should be opened in write mode!'

    try:
      out.write(''.join(('#',header,'\n')))
      # Write timestamp
      tstamp = time.strftime('%a %b %d %H:%M:%S %Z %Y', time.localtime())
      out.write(''.join(('#',tstamp,'\n')))
      # Write properties from the pristine dictionary
      for prop, val in self._origprops.items():
        out.write(''.join((prop,'=',self.escape(val),'\n')))

      out.close()
    except IOError, e:
      raise

  def getPropertyDict(self):
    return self._props

  def __getitem__(self, name):
    """ To support direct dictionary like access """

    return self.getProperty(name)

  def __setitem__(self, name, value):
    """ To support direct dictionary like access """

    self.setProperty(name, value)

  def __getattr__(self, name):
    """ For attributes not found in self, redirect
    to the properties dictionary """

    try:
      return self.__dict__[name]
    except KeyError:
      if hasattr(self._props,name):
        return getattr(self._props, name)

if __name__=="__main__":
  p = Properties()
  p.load(open('test2.properties'))
  p.list()
  print p
  print p.items()
  print p['name3']
  p['name3'] = 'changed = value'
  print p['name3']
  p['new key'] = 'new value'
  p.store(open('test2.properties','w'))

当然,测试这个类你需要在程序目录下简历test2.properties 文件。才可以看到效果,基本可以达到用python 读写 properties 文件的效果.

补充知识:python修改配置文件某个字段

思路:要修改的文件filepath

将修改后的文件写入f2,删除filepath,将f2名字改为filepath,从而达到修改

修改的字段可以参数化,即下面出现的 lilei 可以参数化

imort os
tag=“jdbc.cubedata.username=”
midifyInfo=“jdbc.cubedata.username=lilei”
f1=filepath
f2=application.application
fileInfo=open(filepath)

以上这篇在python中修改.properties文件的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • GDAL 矢量属性数据修改方式(python)

    Case:需要给一个现有的shp数据创建一个字段,并将属性表中原有的一个文本类型的属性转换为整型后填入新创建的字段. Problem:新字段创建成功,但是赋值操作无效,即无法成功给字段写入值. solution:对字段进行赋值后需要,重新写入Feature,否则赋值无效,即layer0.SetFeature(feature). 特别注意:在对数据进行读写操作,一定要以读写的方式打开,即Open(filePath,1),该方法的原型为Open(pszName,int bUpdate = false

  • python修改文件内容的3种方法详解

    这篇文章主要介绍了python修改文件内容的3种方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.修改原文件方式 def alter(file,old_str,new_str): """ 替换文件中的字符串 :param file:文件名 :param old_str:就字符串 :param new_str:新字符串 :return: """ file_data = "&qu

  • Python 修改列表中的元素方法

    如下所示: #打印列表文件 def show_magicians(magics) : for magic in magics : print(magic) #修改列表文件 def make_great(magics) : length=len(magics) for a in range(1,length+1) : magics[a-1]='the Great'+magics[a-1] #输入信息 def input_name(magics) : n=input('请输入魔术师的个数 : ')

  • Python中修改字符串的四种方法

    在Python中,字符串是不可变类型,即无法直接修改字符串的某一位字符. 因此改变一个字符串的元素需要新建一个新的字符串. 常见的修改方法有以下4种. 方法1:将字符串转换成列表后修改值,然后用join组成新字符串 >>> s='abcdef' #原字符串 >>> s1=list(s) #将字符串转换为列表 >>> s1 ['a', 'b', 'c', 'd', 'e', 'f'] #列表的每一个元素为一个字符 >>> s1[4]='

  • 在python中修改.properties文件的操作

    在java 编程中,很多配置文件用键值对的方式存储在 properties 文件中,可以读取,修改.而且在java 中有 java.util.Properties 这个类,可以很方便的处理properties 文件, 在python 中虽然也有读取配置文件的类ConfigParser, 但如果习惯java 编程的人估计更喜欢下面这个用python 实现的读取 properties 文件的类: """ A Python replacement for java.util.Pro

  • python中查看.db文件中表格的名字及表格中的字段操作

    1.问题描述: 我桌面上有一个"账号密码.db"文件,我现在想知道里面有几张表格table.表格的名字.表头结构. 2.使用SQL语句"""select name from sqlite_master where type='table' order by name""",查找表格的名字.实例代码如下: # coding:utf-8 import sqlite3 conn = sqlite3.connect("C:\

  • 使用python批量修改XML文件中图像的depth值

    最近刚刚接触深度学习,并尝试学习制作数据集,制作过程中发现了一个问题,现在跟大家分享一下.问题是这样的,在制作voc数据集时,我采集的是灰度图像,并已经用labelimg生成了每张图像对应的XML文件.训练时发现好多目标检测模型使用的训练集是彩色图像,因此特征提取网络的输入是m×m×3的维度的图像.所以我就想着把我采集的灰度图像的深度也改成3吧.批量修改了图像的深度后,发现XML中的depth也要由1改成3才行.如果重新对图像标注一遍生成XML文件的话太麻烦,所以就想用python批量处理一下.

  • python批量修改xml文件中的信息

    目录 项目场景: 问题描述: 分析: 解决方案: 总结 项目场景: 在做目标检测时,重新进行标注会耗费大量的时间,如果能够批量对xml中的信息进行修改,那么将会节省大量的时间,接下来将详细介绍如何修改标注文件xml中的相关信息. 问题描述: 例如:当我有一批标注好的xml文件,文件格式如下图所示 : <?xml version='1.0' encoding='us-ascii'?> <annotation> <folder>VOC2012</folder>

  • Python中__init__.py文件的作用详解

    __init__.py 文件的作用是将文件夹变为一个Python模块,Python 中的每个模块的包中,都有__init__.py 文件. 通常__init__.py 文件为空,但是我们还可以为它增加其他的功能.我们在导入一个包时,实际上是导入了它的__init__.py文件.这样我们可以在__init__.py文件中批量导入我们所需要的模块,而不再需要一个一个的导入. # package # __init__.py import re import urllib import sys impo

  • Python matplotlib修改默认字体的操作

    matplotlib库作为Python常用的数据可视化库,默认字体居然不支持中文字体,必须得吐槽一下~ 闲言少叙,开始正文 方法1:在plot中指定prop参数 使用matplotlib.font_manager下的FontProperties加载中文字体 调用函数时通过prop属性指定中文字体 import matplotlib.pyplot as plt import matplotlib.font_manager as fm x_data = ['2011', '2012', '2013'

  • python中关于py文件之间相互import的问题及解决方法

    目录 问题背景 实例演示 问题背景 调试脚本时,遇到一个问题:ImportError: cannot import name 'A' from 'study_case.a' (/Users/rchera/PycharmProjects/test/study_case/a.py) 具体情况是这样婶儿的: 前些日子写了一个py文件,它的功能主要是创建数据(暂且称为create_data.py,每条数据会生成一个唯一的id): 同时写了另一个py文件,它的功能主要是操作数据,例如对数据进行编辑.删除等

  • Python中11种NumPy高级操作总结

    目录 1.数组上的迭代 2.数组形状修改函数 1.ndarray.reshape 2.ndarray.flat 3.ndarray.flatten 3.数组翻转操作函数 1.numpy.transpose 2. numpy.ndarray.T 3.numpy.swapaxes 4.numpy.rollaxis 4.数组修改维度函数 1.numpy.broadcast_to 2.numpy.expand_dims 3.numpy.squeeze 5.数组的连接操作 1.numpy.stack 2.

  • Java 对 Properties 文件的操作详解及简单实例

    Java 对 Properties 文件的操作 简介 在 Java 中,我们常用 java.util.Properties.Properties 类来解析 Properties 文件,Properties 格式文件是 Java 常用的配置文件,它用来在文件中存储键-值对,其中键和值用等号分隔,格式如下: name=shawearn Properties 类是 java.util.Hashtable<Object, Object> 的子类,用于键和值之间的映射. 在对 Properties 格式

  • 详解五种方式让你在java中读取properties文件内容不再是难题

    一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC+Mybatis整合开发的项目中通过java程序读取properties文件内容的方式进行了梳理和分析,先和大家共享. 二.项目环境介绍 Spring 4.2.6.RELEASE SpringMvc 4.2.6.RELEASE Mybatis 3.2.8 Maven 3.3.9 Jdk 1.7 Id

随机推荐