内置模块-configparser

configparser 操作配置文件模块

 

创建一个配置文件

 

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'}
config['path'] = {
    'Base_Path' : 'E:\s17\day28\周末作业讲解',
    'students_path' :'E:\s17\day28\周末作业讲解\students'
}
with open('example.ini', 'w',encoding='utf-8') as configfile:
   config.write(configfile)

 

执行结果:

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no

[path]
base_path = E:\s17\day28\周末作业讲解
students_path = E:\s17\day28\周末作业讲解\students
文件名是example.ini
import configparser
config = configparser.ConfigParser()
print(config.sections())        # 结果为[],因为此时还没有打开这个文件

config.read('example.ini')
print(config.sections())        #  查看的是分组名,默认的不打印 ['bitbucket.org', 'topsecret.server.com', 'path']

print('bytebong.com' in config)   # False  判断这个组名在不在这个文件中
print('bitbucket.org' in config)  # True   判断这个组名在不在这个文件中

print(config['bitbucket.org']["user"])  # hg  查看分组中的配置项
print(config['DEFAULT']['Compression']) #yes  查看分组中的配置项
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

 

posted @ 2019-02-08 00:08  小萍瓶盖儿  阅读(101)  评论(0编辑  收藏  举报