当前位置: 代码迷 >> 综合 >> Python3 配置文件(configparser)
  详细解决方案

Python3 配置文件(configparser)

热度:96   发布时间:2023-11-04 09:25:35.0

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'])
  相关解决方案