一、配置文件介绍
ini格式配置文件一般为windows下的配置文件
INI ”就是英文 “initialization”的头三个字母的缩写,后缀为".ini"也可以是".cfg",".conf ”或者是".txt"
ini文件包括三种元素:section,option,comment
1、section
类似分组,已中括号“[]”来命名分组名,
例:[sectionname]
2、option
配置文件里存储信息的主要元素,以key-value形式存储信息
例:name=xiaobailong
3、comment
注释语句,以分号“;”开头,每个注释语句只能占一行,不能分行
例:
;i am comment
二、解析配置文件
python读取ini配置文件可以使用自带的configparser库
configparser使用之前需要实例化
import configparser
config= configparser.ConfigParser()
1、读取
-read(filename) 直接读取文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
'optionname' in config #可以判断一个元素是否在配置文件中
2、写入
方法一:
fp = open(filepath, 'w') #打开文件
config['info'] = {} #添加section
config['info']['name'] = 'xiaobailong' #添加option值
config.write(fp) #写入到文件
方法二:
-write(fp) 将config对象写入到文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
-remove_section(section) 删除某个 section
-remove_option(section, option)
上面的方法并没有将修改写入到文件里去,最后需要调用write将内容写入配置文件
没有找到可以直接修改section名字的方法,如果需要修改section名字,可以删除后重建
#!/usr/bin/env python #coding=utf-8 import configparser class readConfig: def __init__(self,filepath): self.filepath = filepath self.config = configparser.ConfigParser() self.config.read(self.filepath) def read_option(self,section,name): value = self.config.get(section,name) return value def read_sections(self): section_list = self.config.sections() return section_list def read_items(self,section): items_list = self.config.items(section) return items_list class writeConfig: def __init__(self,filepath): self.filepath = filepath self.config = configparser.ConfigParser() self.config.read(self.filepath) self.fp = open(self.filepath,'w') def set_option(self,section,name,value): self.config.set(section,name,value) def add_section(self,section): self.config.add_section(section) def add_option(self,section,option,value): self.config.set(section,option,value) def write(self): #修改配置文件结束后都需要调用改方法写入到配置文件 self.config.write(self.fp) if __name__ == '__main__': rc = readConfig(r"D:\GitHub\config.ini") host = rc.read_option('DATABASE', 'host') items = rc.config.items('DATABASE') print(items) wc = writeConfig(r"D:\GitHub\config.ini") wc.add_section('info') wc.add_option('info','name','xiaobialong') wc.set_option('info','name','xiaobialong2') wc.write()
附:
打开文件的常见方式:
访问模式 | 说明 |
r | 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 |
w | 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
a | 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 |
r+ | 打开一个文件用于读写。文件指针将会放在文件的开头。 |
w+ | 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 |
如果需要以二进制格式打开,加“b”即可,如“rb”
有个疑问:
使用“a”方式时,会把文件里之前的内容重新写入到文件,导致重复,不知道为什么,所以上面代码里用的“w”