国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Python:解析properties文件

2019-11-14 12:53:06
字體:
供稿:網(wǎng)友

在項(xiàng)目中遇到解析PRoperties的情況,而Python中正好沒有解析properties文件的現(xiàn)成模塊,于是從網(wǎng)上找到了這個(gè)腳本,有一些小地方修改了一下

原博客: Python讀寫properties文件

import reimport osimport tempfileclass 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

使用方式:

file_path = 'xxx.properties'props = property.parse(file_path) #讀取文件props.put('key_a', 'value_a') #修改/添加key=valueprint props.get('key_a') #根據(jù)key讀取valueprint "props.has_key('key_a')=" + str(props.has_key('key_a')) #判斷是否包含該key

參考: Python實(shí)用腳本(1):讀取Properties文件


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 商南县| 万盛区| 长寿区| 武强县| 靖州| 冷水江市| 正宁县| 全椒县| 比如县| 兴业县| 柳林县| 平原县| 乡城县| 永平县| 泸定县| 磐安县| 常州市| 平安县| 博客| 嘉鱼县| 清徐县| 兖州市| 杭州市| 高阳县| 扶沟县| 罗甸县| 科技| 乾安县| 宣城市| 上饶市| 揭西县| 清新县| 五莲县| 东至县| 同德县| 张家口市| 阿城市| 阳东县| 天镇县| 巨鹿县| 龙井市|