亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 編程 > Python > 正文

python中修改.properties文件方法

2019-11-06 06:50:48
字體:
來源:轉載
供稿:網友

java 編程中,很多配置文件用鍵值對的方式存儲在 PRoperties 文件中,可以讀取,修改。而且在java 中有 java.util.Properties 這個類,可以很方便的處理properties 文件, 在python 中雖然也有讀取配置文件的類ConfigParser, 但如果習慣java 編程的人估計更喜歡下面這個用python 實現的讀取 properties 文件的類:

"""A Python replacement for java.util.Properties classThis is modelled as closely as possible to the Java original. """import sys,osimport reimport timeclass 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 sclass 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 文件的效果.


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
欧美最近摘花xxxx摘花| 一本色道久久88亚洲综合88| 国产亚洲精品久久久久动| 国产区精品在线观看| 亚洲成人在线视频播放| 日韩激情av在线播放| 国产丝袜一区二区三区免费视频| 2019中文在线观看| 欧美重口另类videos人妖| 亚洲乱码国产乱码精品精天堂| 高清亚洲成在人网站天堂| 国产精品久久久久国产a级| 欧美高清自拍一区| y97精品国产97久久久久久| 尤物yw午夜国产精品视频明星| 欧美成人精品在线视频| 欧美激情精品久久久久久变态| 久久久久久久久久久成人| 国产精品成久久久久三级| 美女精品久久久| www.精品av.com| 国产精品久久久久久av下载红粉| 成人黄色午夜影院| 久久影院免费观看| 欧美日韩性生活视频| 黄色成人av网| 国产精品露脸自拍| 一夜七次郎国产精品亚洲| 欧洲美女7788成人免费视频| 久久免费精品视频| 日韩av日韩在线观看| 亚洲网站视频福利| 久久久久久噜噜噜久久久精品| 91高清视频免费| 亚洲国产精彩中文乱码av在线播放| 亚洲香蕉成视频在线观看| 国产精品揄拍一区二区| 91久久久久久久久久久久久| 国产亚洲精品一区二区| 最近2019免费中文字幕视频三| 92版电视剧仙鹤神针在线观看| 国产精品美腿一区在线看| 色777狠狠综合秋免鲁丝| 欧美日本啪啪无遮挡网站| 中文字幕亚洲欧美一区二区三区| 亚洲综合小说区| 性欧美长视频免费观看不卡| 欧美激情精品久久久久久蜜臀| 欧美性猛交丰臀xxxxx网站| 成人激情视频在线播放| 亚洲a∨日韩av高清在线观看| 成人黄色大片在线免费观看| 亚洲精品456在线播放狼人| 国产激情视频一区| 91香蕉嫩草影院入口| 国产97在线|亚洲| 亚洲第一精品电影| 日韩av中文字幕在线播放| 欧美成年人视频网站欧美| 成人精品一区二区三区电影黑人| 一区二区三区视频免费在线观看| 亚洲xxxxx性| xxxxxxxxx欧美| 久久男人av资源网站| 92看片淫黄大片看国产片| 国产成人拍精品视频午夜网站| 久久精品亚洲热| 久久午夜a级毛片| 亚洲精品videossex少妇| 国产精品欧美日韩久久| 成人精品在线视频| 法国裸体一区二区| 欧美色另类天堂2015| 日韩在线免费视频观看| 亚洲国产精品专区久久| 中文字幕日韩电影| 国产精品一二区| 91久久久久久久一区二区| 一区二区三区美女xx视频| 欧美激情国产高清| 中文字幕免费国产精品| 91sao在线观看国产| 91香蕉嫩草影院入口| 午夜精品久久17c| 欧美诱惑福利视频| 国产精品欧美一区二区| 麻豆国产精品va在线观看不卡| 欧美日韩一区二区精品| 日韩久久免费电影| 欧美黑人一级爽快片淫片高清| 精品国产91久久久久久| 91免费的视频在线播放| 久久久久中文字幕| 狠狠躁夜夜躁人人躁婷婷91| 69国产精品成人在线播放| 伊人久久综合97精品| wwwwwwww亚洲| 亚洲精品中文字| 日韩视频永久免费观看| 欧美日韩国产一区二区三区| www.亚洲男人天堂| 久久99精品视频一区97| 青青久久av北条麻妃海外网| 国产日韩欧美成人| 久久久噜噜噜久噜久久| 欧美一区二区三区……| 国产精品精品久久久| 日韩av在线直播| 久久av资源网站| 久久久久久久久久国产精品| 亚洲人成电影网站色| 庆余年2免费日韩剧观看大牛| www.久久色.com| 九九久久久久久久久激情| 亚洲视频999| 97在线观看视频国产| 国产精品aaaa| 亚洲国产又黄又爽女人高潮的| 欧美成人一二三| 日韩精品在线免费观看视频| 青草热久免费精品视频| 国产一区二区色| 久热国产精品视频| 国产精品一区电影| 亚洲wwwav| 国产精品午夜一区二区欲梦| 中国china体内裑精亚洲片| 亚洲欧洲日韩国产| 亚洲国产精品成人av| 91精品成人久久| 亚洲精品国产电影| 欧美精品久久久久久久久| 精品偷拍各种wc美女嘘嘘| 日韩禁在线播放| 欧美寡妇偷汉性猛交| 88国产精品欧美一区二区三区| 亚洲人成网7777777国产| 欧美一级高清免费播放| 成人精品aaaa网站| 98精品在线视频| 国产性色av一区二区| 国产精品777| 久久久国产影院| 日韩av中文在线| 精品女同一区二区三区在线播放| 最近2019中文字幕一页二页| 亚洲色图五月天| 欧美日韩日本国产| 欧美剧在线观看| 国产婷婷97碰碰久久人人蜜臀| 精品久久久久久久久久久| 亚洲日本aⅴ片在线观看香蕉| 国产精品扒开腿做爽爽爽男男| 国产精品欧美久久久| 成人精品视频久久久久| 2019中文字幕在线观看| 57pao成人永久免费视频| 亚洲va欧美va在线观看| 国产在线精品播放| 亚洲欧洲国产伦综合| 亚洲欧美制服丝袜| 欧美性色19p| 97在线视频免费观看| 日韩中文字幕在线看|