configparser在python3中怎么用

2023-05-14,

这篇文章主要介绍了configparser在python3中怎么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

1.创建configparser文件

import configparser
    #导入模块
config = configparser.ConfigParser()  #注意大小写与()
config['DEFAULT'] = {'Server': '45', 'Compression': 'yes'}
config['server'] = {'deletehq':'0',
                    'localtime':'20180706',
                    'port':'22'}
config['system'] = {'market64':'xiadan1.exe',
                    'market128':'xiadan2.exe',
                    'market256':'xiadan3.exe' }
config['client'] = {}

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

或者通过字典创建

config = configparser.ConfigParser()
config.read_dict(   {
                'section1': {'key1': 'value1',
                                    'key2': 'value2',
                                    'key3': 'value3'},
                'section2': {'keyA': 'valueA',
                                 'keyB': 'valueB',
                                 'keyC': 'valueC'},
                 'section3': {'foo': 'x',
                                    'bar': 'y',
                                  'fun: 'z'}
                                    }   )
with open('configTest1.ini', 'w') as configfile:
    config.write(configfile)

2.读取配置文件

config.read('configTest.ini')
[DEFAULT]
server = 45
compression = yes

[server]
deletehq = 0
localtime = 20180706
port = 22

[system]
market64 = xiadan1.exe
market128 = xiadan2.exe
market256 = xiadan3.exe

[client]

3.读取操作

获取所有sections
print(config.sections())
['server', 'system', 'client']

获取指定 section 的 keys & values
print(config.items('system'))
[('server', '45'), ('compression', 'yes'), ('market64', 'xiadan1.exe'), ('market128', 'xiadan2.exe'), ('market256', 'xiadan3.exe')]  # 注意items()返回的字符串会全变成小写

获取指定 section 的 keys
print(config.options('system'))
['market64', 'market128', 'market256', 'server', 'compression'] #会打印default中的keys

获取指定 key 的 value
print(config['system']['market64'])
xiadan1.exe

4.检查

‘section’ in config

‘option’ in config['section']

config.has_section['section']
config.hais_option['section','option']

5.添加

config.add_section('section4') 
config.set('section4','key1','value1')
config.write(open('configTest1.ini','w'))  #写入

[section4]
key1 = value1

6.删除

config.remove_option('section4','key1') #删除option
config.remove_section('section4') #删除section

7.[DEFAULT]
[DEFAULT] 一般包含 ini 格式配置文件的默认项,所以 configparser 部分方法会自动跳过这个 section 。 sections() 是获取不到的,还有删除方法对 [DEFAULT] 也无效,但指定删除和修改 [DEFAULT] 里的 keys & values 是可以的,还有个特殊的是,has_section() 也无效,可以和 in 区别使用。

感谢你能够认真阅读完这篇文章,希望小编分享的“configparser在python3中怎么用”这篇文章对大家有帮助,同时也希望大家多多支持本站,关注本站行业资讯频道,更多相关知识等着你来学习!

《configparser在python3中怎么用.doc》

下载本文的Word格式文档,以方便收藏与打印。