Python读写INI配置文件完整示例
本文介绍使用Python标准库ConfigParser实现INI配置文件的读写操作。通过封装ConfigFile类,提供获取指定节键值及设置新值的接口,并包含完整的测试代码示例,帮助开发者快速掌握配置文件处理技巧。
本文通过一个具体实例,详细讲解如何在Python中实现INI配置文件的读取与写入功能。以下内容供广大开发者参考借鉴,旨在提供清晰的操作思路。
# -*- coding: utf-8 -*-
import ConfigParser
import os
'''读写配置文件的类
[section]
logpath = D:\log\
imageminsize = 200
'''
class ConfigFile:
'''构造函数:初始化'''
def __init__(self,fileName):
fileName = unicode(fileName,'utf8')
self.flag = False
if os.path.isfile(fileName):
self.fileName = fileName
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.fileName)
self.flag = True
'''获取节为section,键值为Key的值'''
def GetValue(self,Section, Key):
if self.flag:
try:
result = self.cf.get(Section, Key)
return result
except Exception,e:
print e
return ""
else:
return ""
def SetValue(self,Section, Key,Value):
if self.flag:
try:
self.cf.set(Section, Key, Value)
self.cf.write(open(self.fileName, "w"))
except Exception,e:
print e
return ""
#测试代码
configfile = os.path.join(os.getcwd(),'config.conf')
cf = ConfigFile(configfile)
print cf.GetValue("section","logpath")
cf.SetValue("section","imageminsize","200")
如果您对Python的其他技巧感兴趣,建议进一步查阅本站的相关专题,包括《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》,以获取更全面的技术支持。
期望上述关于Python程序设计的介绍能为您提供实际帮助,助力您的开发工作。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













