configparse模块
创建config文件:
import configparser config=configparser.ConfigParser() #config={} #----调用configparser下的一个类去实例化一个对象,命名为config config["DEFAULT"]={'ServerAliveInterval':"45", 'Compression':'yes', 'CompressionLevel':'9'} config['bitbucket.org']={} config['bitbucket.org']['User']='hg' config['topsecret.server.com']={} topsecret=config['topsecret.server.com'] topsecret['Host Port']='50022' topsecret['ForwardXll']='no' with open('confile','w') as configfile: config.write(configfile)
运行结果:
#confile
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardxll = no
-------------------------------增删改查--------------------------------
-------------------------------查:
import configparser config=configparser.ConfigParser() # print(config.sections()) #[] config.read('confile') #把文件和config对象联系起来 print(config.sections()) #['bitbucket.org', 'topsecr print('bytebong.com' in config) #False print(config['bitbucket.org']['User']) #hg (大小写 for key in config['bitbucket.org']: print(key) #default这个键的特殊性,无论遍历那个键,它都会跟着遍历 # user # serveraliveinterval # compression # compressionlevel print(config.options('bitbucket.org')) #遍历这个键 #['user', 'serveraliveinterval', 'compression', 'compress print(config.items('bitbucket.org')) #键值对 #[('serveraliveinterval', '45'), ('compression', 'yes'), print(config.get('bitbucket.org','compression')) #yes
----------------------------------删,改,增
config.add_section("yuan") #添加块 config.set("yuan","name","alex") #添加键值对 config.remove_section('topsecret.server.com') config.remove_option('bitbucket.org','user') config.write(open("i.cfg","w"))
运行结果:
i.cfg:
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 [bitbucket.org] [yuan] name = alex