python_模块_configparser

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/4/18 9:25
# @Author  : chen
# @File    : congigparser_moudle.py
# @Software: PyCharm



# 创建文件
import configparser
config = configparser.ConfigParser()  # 创建对象,调用configparser解析器(我自己的理解)

config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11': 'yes'
                     }
config['bitbuck et.org'] = {'User': 'hg'}
config['topsecret.server.com'] = {'Host Port': '50022', 'ForwardX11': 'no'}
with open('example.ini', 'w') as configfile:
    config.write(configfile)


# 查找文件
# import configparser
#
# config = configparser.ConfigParser()
# print('aaaaaaa', config.sections())  # 刚开始获取为空
# config.read('example.ini')
# print(config.sections())  # 读取文件里的组
# # 此时组里的[DEFAULT]组没有显示出来
# print('bytebong.com' in config)  # False
# print('bitbuck et.org' in config)  # True,这里应该是bitbucket.org
# # 保留下来,表示有空格也能识别,只是指定的时候也需要加空格
# print(config['bitbuck et.org']['user'])  # hg
# print(config['DEFAULT']['Compression'])  # yes
# print(config['topsecret.server.com']['ForwardX11'])  # no,存储forwardx11不区分大小写
# print(config['bitbuck et.org'])  # 返回<Section: bitbuck et.org>
# print('=============')
# for k in config['bitbuck et.org']:  # 注意,有default会默认default的键
#     print(k)
# print(config.options('bitbuck et.org'))  # 同for循环,找到'biubuck et.org'下的所有键
# # 返回的额结果是列表,与for是这个区别
# print('last line:', config.get('bitbuck et.org', 'compression'))  # yes   get方法Section下的key对应的value


# 增删改操作

import configparser

config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')
config.remove_section('bitbuck et.org')  # 删除组section
config.remove_option('topsecret.server.com', 'forwardx11')  # 删除组里的项option
config.set('topsecret.server.com', 'k1', '11111')
config.set('yuan', 'k2', '22222')
config.write(open('new2.ini', 'w'))  # 操作都是在内存中,不写入文件文件不变

猜你喜欢

转载自blog.csdn.net/u013193903/article/details/80178015