Python3 配置文件(configparser)

1.製作一個配置文件

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                    'Compression': 'yes',
                     'CompressionLevel': '9'}
config['DEFAULT']['ForwardX11'] = 'yes'
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
with open('example.ini', 'w') as configfile:
    config.write(configfile)

生成example.ini文件內容如下:

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

[bitbucket.org]
user = hg

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

2.讀此配置文件

import configparser
config = configparser.ConfigParser()
print(config.sections())
config.read('example.ini')
print(config.sections())
print('bitbucket.org' in config)
print('bytebong.com' in config)
print(config['bitbucket.org']['User'])
print(config['DEFAULT']['Compression'])
topsecret = config['topsecret.server.com']
print(topsecret['ForwardX11'])
print(topsecret['Port'])
for key in config['bitbucket.org']:
    print(key)
print(config['bitbucket.org']['ForwardX11'])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章