Python Configparser Module

Source: Internet
Author: User

Used to build and modify common configuration documents
import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,   # 方法一:增加一个 default setion                     ‘Compression‘: ‘yes‘,                     ‘CompressionLevel‘: ‘9‘}config[‘klvchen.com‘] = {}                          # 方法二:增加一个 klvchen.com setionconfig[‘klvchen.com‘][‘User‘] = ‘kl‘config[‘topsecret.server.com‘] = {}                 # 方法三:添加一个 topsecret.server.comtopsecret = config[‘topsecret.server.com‘]topsecret[‘Host Port‘] = ‘50022‘     topsecret[‘ForwardX11‘] = ‘no‘  with open(‘example.ini‘, ‘w‘) as configfile:   config.write(configfile)

Generate the Example.ini document in the current directory:

[DEFAULT]compressionlevel = 9compression = yesserveraliveinterval = 45[klvchen.com]user = kl[topsecret.server.com]host port = 50022forwardx11 = no
Common operations
import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)# 获取 DEFAULT 的键值print(config.defaults())运行结果:OrderedDict([(‘compressionlevel‘, ‘9‘), (‘compression‘, ‘yes‘), (‘serveraliveinterval‘, ‘45‘)])# 获取除 DEFAULT 外的 setionprint(config.sections()) 运行结果: [‘bitbucket.org‘, ‘topsecret.server.com‘]# 判断 setion 是否存在print(‘klvchen.com‘ in config)运行结果: Trueprint(config.has_section(‘klvchen.com‘))运行结果: True# 获取 setion 中的某个键值print(config[‘klvchen.com‘][‘User‘])运行结果: klprint(config[‘DEFAULT‘][‘compression‘])运行结果: yes# 获取所有的 setion,包括 defaultfor key in config:    print(key)运行结果:DEFAULTklvchen.comtopsecret.server.com# 删除setionconfig.remove_section(‘topsecret.server.com‘)  # 整个setion下的键值对都会删除config.write(open(‘example.ini‘, ‘w‘))         # 需要重新写入文件# klvchen.com setion 下修改键值,没有即添加 config.set(‘klvchen.com‘, ‘age‘, ‘28‘)config.write(open(‘example.ini‘, ‘w‘))         # 需要重新写入文件

Python Configparser Module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.