温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

configparser在python3中怎么用

发布时间:2021-10-18 11:57:13 阅读:189 作者:小新 栏目:编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这篇文章主要介绍了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中怎么用”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×