python提供了ConfigParser模块来解析配置文件,它解析的配置文件格式类似于ini配置文件,文件被分成若干个section,每个section中有具体的配置信息,例如
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb=true
其中mysqldb就是一个section,ConfigParser模块需要通过section才能对其中的配置进行插入,更新,删除等操作。那对于没有section的配置文件应该怎么处理呢,例如配置文件是这样的:
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb=true
在这里提供的解决方案是:在处理配置文件第一行手工加入section标识,在处理完成之后,再将第一行删除,具体代码如下:
def _add_section(self, file_name, section="[default]"):
conf_list = open(file_name).read().split("\n")
conf_list.insert(0, section)
fp = open(file_name, "w")
fp.write("\n".join(conf_list))
fp.close()
def _clear_section(self, file_name):
conf_list = open(file_name).read().split("\n")
conf_list.pop(0)
fp = open(file_name, "w")
fp.write("\n".join(conf_list))
fp.close()
def set_property(self, key, value, file_name):
self._add_section(file_name)
c = ConfigParser.ConfigParser()
c.optionxform = str
c.read(file_name)
c.set("default", key, value)
c.write(open(file_name, "w"))
self._clear_section(file_name)
其中_add_section中增加了section,命名为default,_clear_section删除了default这个section标识。在set_property就可以调用ConfigParser的set方法(或其他方法)对属性进行操作。