python之configparser模块
configparser模块
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
创建文件
使用下面的Python文件就可以创建一个与之对应的.ini文件
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11': 'yes' } config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} with open('example.ini', 'w') as configfile: config.write(configfile)
生成的文档内容:
[DEFAULT] compression = yes forwardx11 = yes compressionlevel = 9 serveraliveinterval = 45 [bitbucket.org] user = hg [topsecret.server.com] forwardx11 = no host port = 50022
查找文件
import configparser config = configparser.ConfigParser() #---------------------------查找文件内容,基于字典的形式 print(config.sections()) # 查看所有的节,但是默认不显示defaul节[] config.read('example.ini') print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] print('bytebong.com' in config) # False print('bitbucket.org' in config) # 验证某个节是否在文件中 True print(config['bitbucket.org']["user"]) # 查看某个节下面的某个配置的值hg print(config['DEFAULT']['Compression']) #yes 看是否有default的节 print(config['topsecret.server.com']['ForwardX11']) #no print(config['bitbucket.org']) # 判断是否可迭代 <Section: bitbucket.org> # for key in config['bitbucket.org']: # 注意,有default会默认default的键 print(key) print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对 print(config.get('bitbucket.org','compression')) # yes get方法Section下的key对应的value
增删改操作
import configparser config = configparser.ConfigParser() config.read('example.ini') config.add_section('yuan') config.remove_section('bitbucket.org') config.remove_option('topsecret.server.com',"forwardx11") config.set('topsecret.server.com','k1','11111') config.set('yuan','k2','22222') config.write(open('new2.ini', "w"))
注意:
#section 可以直接操作它的对象来获取所有的信息
#option 可以通过找到的节点查看多有的项
class Configparser: def __init__(self,section,option): self.section = section self.option = option def write(self,f): f.write(self.section,self.option) f = open('test','w') config = Configparser('a','b') config.write(f)

浙公网安备 33010602011771号