python configparser处理.ini配置文件

配置文件(.ini)有两种格式:

session
1.key=value
2.key:value

建立一个ini文件测试,内容如下:

[jingdong]
loca=beijing
boss=liuqiangdong
[Alibaba]
loca=hangzhou
boss=mayun
[tecent]
loca=shehzhen
boss=mahuateng
[huawei]
loca=shenzhen
boss=renzhenfei

1.read()函数

def read(self, filenames, encoding=None):
# Read and parse a filename or an iterable of filenames.
# Return list of successfully read files.

使用read()读取文件并遍历section:

import configparser
file_path = "E:/program/python/test/test1/test.ini"
config = configparser.ConfigParser()
config.read(file_path, encoding="gbk")
for x in config:
    print(x)

# DEFAULT
# jingdong
# Alibaba
# tecent
# huawei

2.item()函数

    def items(self, section=_UNSET, raw=False, vars=None):
        """Return a list of (name, value) tuples for each option in a section.

1)获取一个section所有的option

t=config.items("huawei")
print(t)
# [('loca', 'shenzhen'), ('boss', 'renzhenfei')]

2)因为以list形式呈现,当然可以遍历

for x in config.items("huawei"):
    print(x)
# ('loca', 'shenzhen')
# ('boss', 'renzhenfei')

3.add_section()函数

    def add_section(self, section):
        """Create a new section in the configuration.

添加一个新的section:“dajiang”


config.add_section("dajiang")
for x in config:
    print(x)
# DEFAULT
# jingdong
# Alibaba
# tecent
# huawei
# dajiang

不过“dajiang”是没有option的,下面的函数可以添加
4.set()函数,设置每一个option(添加和修改)

    def set(self, section, option, value=None):
        """Set an option."""

新建)

config.add_section("dajiang")
config.set("dajiang","chanpin","wurenji")
print(config.items("dajiang"))
# [('chanpin', 'wurenji')]

修改)

config.set("dajiang","chanpin","hangtianfeiji")
print(config.items("dajiang"))
#[('chanpin', 'hangtianfeiji')]

5.get()函数

    def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
        """Get an option value for a given 

获取section给定的section下的option的值

print(config.get("huawei","boss"))
#renzhengfei

还可以这样获取某个option的等号后面的元素

print(config['huawei']['boss'])
#renzhenfei

6.有增加section自然就有删除,这里的pop()不是常规的删除列表的最后一个元素,而且根据section名称删除

t=config.pop("huawei")
print(t)
for x in config:
    print(x)
# <Section: huawei>
# DEFAULT
# jingdong
# Alibaba
# tecent
# dajiang

不过他没有“记忆性”,前面删除了huawei,再次遍历就又出现了

t=config.pop("jingdong")
print(t)
for x in config:
    print(x)
# <Section: jingdong>
# DEFAULT
# Alibaba
# tecent
# huawei
# dajiang

最后来一次完整的遍历:

t=config.pop("jingdong")
print(t)
for x in config:
    print(config.items(x))
# <Section: jingdong>
# []
# [('loca', 'hangzhou'), ('boss', 'mayun')]
# [('loca', 'shehzhen'), ('boss', 'mahuateng')]
# [('loca', 'shenzhen'), ('boss', 'renzhenfei')]
# [('chanpin', 'hangtianfeiji')]

这个时候会发现我们的文件中并没有任何改动,这时候就需要:
8.write()函数

    def write(self, fp, space_around_delimiters=True):
        """Write an .ini-format representation of the configuration state.
with open(file_path,"w",encoding="gbk") as fw:
    config.write(fw)
for x in config:
    print(config.items(x))
# []
# [('loca', 'beijing'), ('boss', 'liuqiangdong')]
# [('loca', 'hangzhou'), ('boss', 'mayun')]
# [('loca', 'shehzhen'), ('boss', 'mahuateng')]
# [('loca', 'shenzhen'), ('boss', 'renzhenfei')]
# [('chanpin', 'hangtianfeiji')]

学习记录随笔,并不是很完善!
如有不足,欢迎指正和讨论!

猜你喜欢

转载自blog.csdn.net/liulanba/article/details/114586250