Python解析properties脚本

在项目中遇到解析properties的情况,而Python中正好没有解析properties文件的现成模块,于是从网上找到了这个脚本,有一些小地方修改了一下

原博客: Python读写properties文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import re
import os
import tempfile


class Properties:

def __init__(self, file_name):
self.file_name = file_name
self.properties = {}
try:
fopen = open(self.file_name, 'r')
for line in fopen:
line = line.strip()
if line.find('=') > 0 and not line.startswith('#'):
strs = line.split('=')
self.properties[strs[0].strip()] = strs[1].strip()
except Exception, e:
raise e
else:
fopen.close()

def has_key(self, key):
return key in self.properties

def get(self, key, default_value=''):
if key in self.properties:
return self.properties[key]
return default_value

def put(self, key, value):
self.properties[key] = value
replace_property(self.file_name, key + '=.*', key + '=' + value, True)


def parse(file_name):
return Properties(file_name)


def replace_property(file_name, from_regex, to_str, append_on_not_exists=True):
tmpfile = tempfile.TemporaryFile()

if os.path.exists(file_name):
r_open = open(file_name, 'r')
pattern = re.compile(r'' + from_regex)
found = None
for line in r_open:
if pattern.search(line) and not line.strip().startswith('#'):
found = True
line = re.sub(from_regex, to_str, line)
tmpfile.write(line)
if not found and append_on_not_exists:
tmpfile.write('\n' + to_str)
r_open.close()
tmpfile.seek(0)

content = tmpfile.read()

if os.path.exists(file_name):
os.remove(file_name)

w_open = open(file_name, 'w')
w_open.write(content)
w_open.close()

tmpfile.close()
else:
print "file %s not found" % file_name

使用方式:

1
2
3
4
5
file_path = 'xxx.properties'
props = property.parse(file_path) #读取文件
props.put('key_a', 'value_a') #修改/添加key=value
print props.get('key_a') #根据key读取value
print "props.has_key('key_a')=" + str(props.has_key('key_a')) #判断是否包含该key

参考:
Python实用脚本(1):读取Properties文件


-------------本文结束感谢您的阅读-------------
0%