在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'(""" 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'(""" 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文件的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新动态
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]

