configparser模块

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 config['DEFAULT'] = {
 5     'ServerAliveInterval': 45,
 6     'Compression': 'yes',
 7     'CompressionLevel': 9,
 8     'ForwardX11': 'yes'
 9 }
10 config['bit'] = {
11     'bitbucket': 'hg',
12     "User": 'nihoa'
13 }
14 config['SERVER'] = {
15     'PORT': 8080,
16     'PASSWD': 2663
17 }
18 with open('aa.config', 'w') as f:
19     config.write(f)
20 # 增删改查
21 # ---------------------查
22 config = configparser.ConfigParser()  # 创建对象
23 config.read('aa.config')  # 将文件传进对象
24 print(config.sections())  # 打印文件的各个部分
25 print('ok' if 'bit' in config.sections() else 'no')  # 三元表达式
26 print(config['bit']['user'])  # 取出块里面的值
27 for i in config.values():  # 遍历
28     for n in i.keys():
29         print(n)
30     print(i)
31 print(config.items('SERVER'))  # 返回一个列表
32 print(config.get('bit', 'USER'))  # 取值方法
33 # --------------删、改、增
34 config.add_section('yuan')  # 增加一个块
35 config['yuan']['name'] = 'haha'
36 config.set('yuan', 'what', '你是谁')
37 config.write(open('bbb.inin', 'w', encoding='utf-8'))
38 config.remove_option('bit', 'user')  # 删除键值对
39 config.remove_section('bit')  # 删除一个部分
40 config.write(open('ccc.init', 'w'))

 

posted @ 2020-03-05 12:28  竹石2020  阅读(141)  评论(0编辑  收藏  举报