python读写配置文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JohinieLi/article/details/81137156

命令选项说明

1、配置文件的格式
a) 配置文件中包含一个或多个 section, 每个 section 有自己的 option;
b) section 用 [sect_name] 表示,每个option是一个键值对,使用分隔符 = 或 : 隔开;
c) 在 option 分隔符两端的空格会被忽略掉
d) 配置文件使用 # 和 ; 注释

2、读配置文件
import ConfigParser
cf=ConfigParser.ConfigParser()
cf.read(path) 读配置文件(ini、conf)返回结果是列表
cf.sections() 获取读到的所有sections(域),返回列表类型
cf.options(‘sectionname’) 某个域下的所有key,返回列表类型
cf.items(‘sectionname’) 某个域下的所有key,value对
value=cf.get(‘sectionname’,’key’) 获取某个yu下的key对应的value值
cf.type(value) 获取的value值的类型

getint(section, option)
获取section中option的值,返回int类型数据,所以该函数只能读取int类型的值。
getboolean(section, option)
获取section中option的值,返回布尔类型数据,所以该函数只能读取boolean类型的值。
getfloat(section, option)
获取section中option的值,返回浮点类型数据,所以该函数只能读取浮点类型的值。
has_option(section, option)
检测指定section下是否存在指定的option,如果存在返回True,否则返回False。
has_section(section)
检测配置文件中是否存在指定的section,如果存在返回True,否则返回False。

3、动态写配置文件
cf.add_section(‘test’) 添加一个域
cf.set(‘test3’,’key12’,’value12’) 域下添加一个key value对
cf.write(open(path,’w’)) 要使用’w’

简单的示例

python自带的ConfigParser库可以对配置文件进行操作(ini,conf)

有配置文件如下:

[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = xgmtest
[concurrent]
[quession]

对配置文件进行读写操作

#_*_coding:utf-8_*_
#python读取配置文件练习
import ConfigParser
cf = ConfigParser.ConfigParser()

cf.read('test.conf')
#获取所有section,返回值为list
secs = cf.sections()
print secs

#获取db中的所有属性名
dboption=cf.options('db')
print dboption

#获取db中的键值对
dbitem=cf.items('db')
print dbitem

#获取section为db,属性名为db_pass的值
print cf.get('db','db_pass')

#写配置文件
cf.add_section('key_word')
cf.set('key_word','key1','please check connections to the other CEs and your config items')

cf.write(open('test.conf','w'))

完成增删改查等操作的代码

# -*- encoding: utf-8 -*-
'''
@author: Johnie Li
@contact: [email protected]
@file: configfile_operate.py
@time: 2018/7/20 17:11
@desc:
    关于配置文件的读取,修改,添加,删除。
'''
import os
import configparser

def configfile_reader(file_path):
    # 读取配置文件
    config_reader = configparser.ConfigParser()
    config_reader.read(file_path)

    # 获取所有的section,返回是list
    read_sections = config_reader.sections()

    read_list = []

    for section_name in read_sections:

        # 获取所有的属性中的键值对
        read_items = config_reader.items(section_name)

        # 构造读取列表
        for _ in read_items:

            read_list.append((section_name, _[0], _[1]))

    return read_list

def configfile_reader_sections(file_path):
    # 读取配置文件
    config_reader = configparser.ConfigParser()
    config_reader.read(file_path)

    # 获取所有的section,返回是list
    read_sections = config_reader.sections()

    return read_sections

def configfile_reader_option(file_path):
    # 读取配置文件
    config_reader = configparser.ConfigParser()
    config_reader.read(file_path)

    # 获取所有的section,返回是list
    read_sections = config_reader.sections()

    read_list = []

    for section_name in read_sections:

        # 获取所有的属性名
        read_option = config_reader.options(section_name)

        # 构造读取列表
        for _ in read_option:
            read_list.append((section_name, _))

    return read_list

def cofigfile_reader_value(file_path, section_name, option_name):
    # 读取配置文件
    config_reader = configparser.ConfigParser()
    config_reader.read(file_path)

    # 获取配置信息中特定的取值
    return config_reader.get(section_name, option_name)

def configfile_write(file_path, section_add_list):
    # 写入配置文件,如果没有则新建文件,有则添加
    config_writer = configparser.ConfigParser()
    config_writer.read(file_path)

    # 获取所有需要添加的section_name
    section_name_list = [section_add_list[_][0] for _ in range(len(section_add_list))]

    section_name_deduplication = list(set(section_name_list))

    # 添加不重复的section
    for section_name_add in section_name_deduplication:

        if not config_writer.has_section(section_name_add):

            config_writer.add_section(section_name_add)

    # 添加section中的各项信息
    for section_content in section_add_list:

        section_name, option_name, value_value = section_content[0], section_content[1], section_content[2]

        config_writer.set(section_name, option_name, value_value)

    # 写入到配置文件中
    config_writer.write(open(file_path, 'w'))

def configfile_revise(file_path, section_revise_list):
    # 修改配置文件
    config_writer = configparser.ConfigParser()
    config_writer.read(file_path)

    for _ in section_revise_list:

        if config_writer.has_option(_[0], _[1]):

            # 对已有的配置信息做修改
            config_writer.remove_option(_[0], _[1])
            config_writer.set(_[0], _[1], _[2])

        elif not config_writer.has_section(_[0]):

            # 添加没有的配置信息
            config_writer.add_section(_[0])
            config_writer.set(_[0], _[1], _[2])

        else:

            # 添加没有的配置信息
            config_writer.set(_[0], _[1], _[2])

    # 写入到配置文件中
    config_writer.write(open(file_path, 'w'))

def configfile_delete(file_path, section_delete_list):
    # 修改配置文件
    config_writer = configparser.ConfigParser()
    config_writer.read(file_path)

    for _ in section_delete_list:

        if config_writer.has_option(_[0], _[1]):

            # 对已有的配置信息做删除
            config_writer.remove_option(_[0], _[1])

        else:

            # 删除失败
            print('failed to delete!')

    # 写入到配置文件中
    config_writer.write(open(file_path, 'w'))

if __name__ == '__main__':

    # 读取所有的配置信息
    read_list = configfile_reader('./test1.conf')

    print(read_list)

    # 读取所有的section名称
    read_sections = configfile_reader_sections('./test1.conf')

    print(read_sections)

    # 读取所有的section和option的键值对
    read_options = configfile_reader_option('./test1.conf')

    print(read_options)

    # 读取特定的配置属性的值
    read_value = cofigfile_reader_value('./test1.conf', 'id', 'name123')

    print(read_value)

    # 添加配置信息
    section_add_list = [('ip', 'name', 'xiaoli'), ('ip', 'ip', '1.1.1.1'), ('adress', 'path', './c/')]

    configfile_write('./test2.conf', section_add_list)

    # 修改配置信息
    section_revise_list = [('ip', 'name', 'feifei'), ('ip', 'sex', 'nan'), ('phone', 'path', '123'), ('phone', 'number', '110')]

    configfile_revise('./test2.conf', section_revise_list)

    # 删除某一条配置信息
    section_delete_list = [('phone', 'path', '123')]

    configfile_delete('./test2.conf', section_delete_list)

参考文献:
1、https://blog.csdn.net/babyfish13/article/details/64919113 2018.7.20
2、https://blog.csdn.net/qq_38328875/article/details/79653479 2018.7.20
3、https://www.cnblogs.com/emily-qin/p/8022292.html 2018.7.20

猜你喜欢

转载自blog.csdn.net/JohinieLi/article/details/81137156