Python3学习之路~5.11 configparser模块

用于生成和修改常见配置文档,当前模块的名称在 python 2.x 版本中为 ConfigParser, python 3.x 版本中变更为 configparser。

来看一个好多软件的常见文档格式如下

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

import configparser

config = configparser.ConfigParser()

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'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

config['DEFAULT']['ForwardX11'] = 'yes'

with open('example.ini', 'w') as configfile:
    config.write(configfile)

写完了还可以再读出来

import configparser

config = configparser.ConfigParser()

print(config.sections()) # []
config.read('example.ini')
print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
print(config.default_section) # DEFAULT

print('bitbucket.org' in config) # True
print('bytebong.com' in config) # False
print(config.has_section('DEFAULT')) # False
print(config.has_section('topsecret.server.com')) # True

print(config['bitbucket.org']['User']) # hg
print(config.get('bitbucket.org','User')) # hg

print(config['DEFAULT']['Compression']) # yes

topsecret = config['topsecret.server.com']
print(topsecret['ForwardX11']) # no
print(topsecret['host port']) # 50022
print(config.get('topsecret.server.com','host port')) # 50022
print(config.getint('topsecret.server.com','host port')) # 50022

for key in config['bitbucket.org']:
    print(key)
# 输出:
# user
# serveraliveinterval
# compression
# compressionlevel
# forwardx11

print(config.options('bitbucket.org'))
# 输出:['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']

print(config.items('bitbucket.org'))
# 输出:[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

print(config['bitbucket.org']['ForwardX11']) # yes

print(config.defaults())
# 输出:OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
configparser-读

configparser增删改语法

import configparser

config = configparser.ConfigParser()
config.read('example.ini')

# # 删
# config.remove_section('bitbucket.org')
# config.remove_option('topsecret.server.com','forwardx11')
# config.write(open('example2.cfg','w'))

# # 增
# print(config.has_section('newSection')) # False
# config.add_section('newSection')
# config.write(open('example3.cfg', "w"))

#
config.set('bitbucket.org','User','Bob')
config.write(open('example4.cfg','w'))
configparser-增删改

 

posted @ 2018-12-17 14:09  zhengna  阅读(176)  评论(0编辑  收藏  举报