Python核心编程中题目(解析操作Ini配置文件)
来源:互联网 发布:php 字符串截取替换 编辑:程序博客网 时间:2024/06/11 21:13
在核心编程中文件操作一章中的习题有一个要求分析系统的配置文件的习题。根据本习题的要求,随手写了一个Python操作Ini文件的类封装,封装方式类似Delphi的TIniFile的样式。具体代码还有一些不如人意的地方(比如写入配置文件的时候),我是先删除了原文件,然后重新构造,所以加了一个updateIniFile的函数。具体东西也就不多说了,直接贴代码吧:
PythonCode:# -*- coding: gbk -*-#**************#作者:不得闲#2009-02-27#**************import typesimport reimport osimport copyclass PDxIni: """Ini文件解析类库""" def __init__(self,filename): self.sectionReg = r'^/s*/[/w*/]/s*$'#分段正则 self.f = file(filename,'w+') self.sectionValues = [] self.sections = {} self.__paserIni__() self.sectionCount = 0 def __del__(self):#释放时触发 self.updateIniFile() self.f.close() def __paserIni__(self): i = 0 for line in self.f: sectionMatch = re.search(r'^/s*/[/w*/]/s*$',line) line = line.strip() if sectionMatch and (sectionMatch.start()==0): tmpSection = line.replace('[','']).replace('','') self.sectionValues.append(tmpSection) self.sections[tmpSection]={}#本节的数据信息 self.sections[tmpSection]['index'] = i self.sections[tmpSection]['count'] = 0 self.sectionCount = i i += 1 j = 0 else: line = re.sub(';.*','',line)#去掉注释 if tmpSection != '': KeyValue= line.split('=',1) if len(KeyValue) == 2: self.sections[tmpSection][KeyValue[0]] = {} self.sections[tmpSection][KeyValue[0]]['value']=KeyValue[1] self.sections[tmpSection][KeyValue[0]]['index'] = j j += 1 self.sections[tmpSection]['count']= j def __readValue__(self,sectionName,key,defaultvalue): try: ValueList = self.sections[sectionName] try: return ValueList[key]['value'] except: return defaultvalue except: return defaultvalue def readString(self,sectionName,key,defaultvalue): """读取字符串,SectionName指定节点,Key指定关键字,DefaultValue指定默认字符串""" if type(defaultvalue) == types.StringType: return self.__readValue__(sectionName,key,defaultvalue) else: print 'defaultvalue must String' def readInteger(self,sectionName,key,defaultvalue): """读取整数,SectionName指定节点,Key指定关键字,DefaultValue指定整数""" if type(defaultvalue) == types.IntType: return self.__readValue__(sectionName,key,defaultvalue) else: print 'defaultvalue must Integer' def readBool(self,sectionName,key,defaultvalue): """读取Boolean值,SectionName指定节点,Key指定关键字,DefaultValue指定默认Boolean值""" if type(defaultvalue) == types.BooleanType: return self.__readValue__(sectionName,key,defaultvalue) else: 'print defaultvalue must Boolean' def __writeValue__(self,SectionName,Key,Value): try: ValueList = self.sections[SectionName] self.sections[tmpSection]['index'] = self.sectionCount ValueList[Key]['index'] = self.sections[SectionName]['count'] except: self.sectionValues.append(SectionName) self.sections[SectionName] = {} self.sections[SectionName]['index'] = self.sectionCount ValueList = self.sections[SectionName] ValueList['count'] = 1 ValueList[Key] = {} ValueList[Key]['index'] = 0 ValueList[Key]['value'] = Value def writeInteger(self,SectionName,Key,Value): """写入整数,SectionName指定节点,Key指定关键字,Value指定写入数据""" if type(Value) == types.IntType: self.__writeValue__(SectionName,Key,Value) else: print 'error' def writeString(self,SectionName,Key,Value): """写入字符串,SectionName指定节点,Key指定关键字,Value指定写入数据""" if type(Value) == types.StringType: self.__writeValue__(SectionName,Key,Value) else: print 'write String Error' def writeBool(self,SectionName,Key,Value): """写入Boolean,SectionName指定节点,Key指定关键字,Value指定写入数据""" if type(Value) == types.BooleanType: self.__writeValue__(SectionName,Key,Value) else: print 'write Boolean Error' def getSections(self): """获取节点信息""" return self.sectionValues def getSectionKeys(self,SectionName): """获取某个节点下的所有Key信息""" SectionDict = copy.deepcopy(self.sections[SectionName])#使用深拷贝生成一个新的数据 SectionDict.pop('count') SectionDict.pop('index') return [KeyValue[0] for KeyValue in sorted(SectionDict.items(),key=lambda m: m[1]['index'])] def sectionKeyValues(self,SectionName): """获取某个节点下的(Key,Value)信息元祖串""" SectionDict = copy.deepcopy(self.sections[SectionName])#使用深拷贝生成一个新的数据 SectionDict.pop('count') SectionDict.pop('index') return [(KeyValue[0],KeyValue[1]['value']) for KeyValue in sorted(SectionDict.items(),key=lambda m: m[1]['index'])] def updateIniFile(self): filename = self.f.name self.f.close() os.remove(filename) self.f = file(filename,'w+') for SectionDict in sorted(self.sections.items(),key=lambda d: d[1]['index']): #获取排列好顺序的Section self.f.write('[%s]/n'%SectionDict[0])#写入分段 SectionDict[1].pop('index')#弹出排序索引 SectionDict[1].pop('count') if len(SectionDict[1].items()) > 0: for KeyValue in sorted(SectionDict[1].items(),key=lambda m: m[1]['index']): self.f.write('%s=%s/n'%(KeyValue[0],KeyValue[1]['value']))#写入分段 if __name__=='__main__': ini = PDxIni(r'E:/appendDL.ini') ini.writeInteger('test2','java',788) print ini.readInteger('test2','frlphi',22 ) del ini
使用方法和Delphi类似
列入我的系统中执行的效果如下:
- Python核心编程中题目(解析操作Ini配置文件)
- python 3 ini配置文件操作
- python 中对配置文件(如.ini文件)进行读写等操作ConfigParser模块
- Python用ConfigParser解析INI配置文件
- python 3.x 解析 INI配置文件(ConfigParser)
- 配置文件读写操作(.ini)
- python配置文件(ini文件)
- Unity中解析ini配置文件----INIParser
- Delphi中读写INI配置文件操作总结
- Eclipse.ini配置文件解析
- Eclipse.ini配置文件解析
- Qt解析INI配置文件
- 程序配置文件(*.ini)的操作
- ACE操作ini配置文件
- 配置文件INI的操作
- PHP操作ini配置文件
- C# 操作INI配置文件
- MFC操作ini配置文件
- 创建视图要什么权限
- 单例(Singleton)模式
- SAP MM--12(Cross-Company Purchasing)
- 工厂方法(Factory Method)模式
- Oracle数据库的启动和关闭方式小结
- Python核心编程中题目(解析操作Ini配置文件)
- 简单工厂(Simple Factory)模式
- makecab cabwiz 制作PPC中文程序名的安装包;makecab中利用参数设置不压缩,设置带文件夹进行压缩
- SQL学习和积累(一些不常用确很有用的方法)
- Dunk Womens Shoes,Dunk Low SB Shoes,Dunk High SB Shoes
- What is a reasonable pricing for mobile?
- 在ASP.NET中实现AJAX
- RedHat9网络配置入门
- 没有盗版的日子