python 操作 .ini 文件

本文介绍了使用Python的configparser模块来操作.ini配置文件的方法,包括自动创建文件、读取选项、设置默认值、添加选项及修改配置等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. python 操作 .ini 文件封说明

  1. 依赖configparser模块,需要:pip install configparser
  2. 读取文件时如果发现找不到相应的ini文件,代码会自动创建ini文件和目录
  3. 读取ini文件option时,如果找不到相应option时,会有以下两种情况:
    • 如果设置了默认值,则将默认值设置到.ini文件中,并返回默认值
    • 如果没有设置默认值,则返回None,并不会创建option。
  4. 设置option时如果ini文件中没有,则会创建option
  5. 修改配置,可以用设置option完成,只要section和option已经存在,就修改其值

2. 代码和测试用例如下

# pip install configparser  # 安装ini文件读取模块
import os
import configparser

# HOME_PATH = os.path.expanduser('~')    # 获取家目录路径
# print(HOME_PATH)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # 获取当前文件目录
ConfigPath = os.path.join(BASE_DIR, 'config')  # 自己的配置文件路径,根据项目需求,这里是--> 在当前目录下的config下存放目录文件


def create_config_file(file_name):
    """如果配置文件不存在,就新建配置文件"""
    create_file_path = os.path.join(ConfigPath, file_name)
    if not os.path.exists(ConfigPath):
        os.system('mkdir {}'.format(ConfigPath))
        # os.system('chown -R nvidia:nvidia {}'.format(ConfigPath))  # 修改文件夹权限,根据用户进行修改

    if not os.path.exists(create_file_path):
        os.system('touch {}'.format(create_file_path))
        # os.system('chown -R nvidia:nvidia {}'.format(create_file_path))
        # os.system('chmod 660 {}'.format(create_file_path))


def get_config_data(file_name, section, option, option_default_val=None):
    """
    获取本地升级配置信息
    :param file_name: 配置文件名字      必须str类型
    :param section: ini配置文件中的section    必须str类型
    :param option:  ini配置文件中的option    必须str类型
    :param option_default_val: 读取不到配置参数时设置默认值,默认为None不会设置   必须str类型
    :return: 获取到的配置参数(如果获取失败且option_default_val为None时返回None,如果option_default_val不为None,则返回option_default_val)
    """
    create_config_file(file_name)  # 如果配置文件不存在,就新建配置文件
    conf = configparser.ConfigParser()
    file_path = os.path.join(ConfigPath, file_name)
    conf.read(file_path, encoding='utf-8')
    try:
        result = conf.get(section, option)
    except configparser.NoSectionError as e:
        print('NoSection Error:{}'.format(e))
        if option_default_val:
            result = option_default_val
            conf.add_section(section)
            conf.set(section, option, option_default_val)
            with open(file_path, 'w') as f:
                conf.write(f)
        else:
            result = None
    except configparser.NoOptionError as e:
        print('NoOption Error:{}'.format(e))
        if option_default_val:
            result = option_default_val
            conf.set(section, option, option_default_val)
            with open(file_path, 'w') as f:
                conf.write(f)
        else:
            result = None
    return result


def set_config_data(file_name, section, option, option_val):
    """
    设置自动升级模式到配置文件
    :param file_name: 配置文件名字          必须str类型
    :param section: ini配置文件中的section  必须str类型
    :param option:  ini配置文件中的option  必须str类型
    :param option_val: 设置option的值   必须str类型
    :return:
    """
    create_config_file(file_name)  # 如果配置文件不存在,就新建配置文件
    conf = configparser.ConfigParser()
    file_path = os.path.join(ConfigPath, file_name)
    conf.read(file_path, encoding='utf-8')
    try:
        conf.get(section, option)
    except configparser.NoSectionError as e:
        print('NoSection Error:{}'.format(e))
        conf.add_section(section)             # 如果section不存在就添加
    except configparser.NoOptionError as e:
        print('NoOption Error:{}'.format(e))
    finally:
        conf.set(section, option, option_val)
        with open(file_path, 'w') as f:
            conf.write(f)


if __name__ == '__main__':
    set_config_data('test.ini', 'python', 'func', '12')
    get_value = get_config_data('test.ini', 'python', 'func2', 'default_value_35')
    get_value = get_config_data('test.ini', 'python', 'func3')
    print(get_value)
使用
def get_view_config(section, option, option_default_val=None):
    """
    get view config data
    :param section: config file section, mast be string
    :param option:  config file option, mast be string
    :param option_default_val: When dose not get the config value, will set
           default value if this params is not None
    :return: config value
    """
    file_path = "/etc/mass/mass-view-conf.ini"
    conf = configparser.ConfigParser()
    conf.read(file_path, encoding='utf-8')
    try:
        result = conf.get(section, option)
    except configparser.NoSectionError as e:
        logging.error('Dose not get section:{} in view config file,'
                      'NoSectionError: {}'.format(section, e))
        if option_default_val:
            result = option_default_val
            conf.add_section(section)
            conf.set(section, option, option_default_val)
            with open(file_path, 'w') as f:
                conf.write(f)
        else:
            result = None
    except configparser.NoOptionError as e:
        logging.error('Dose not get option:{} in the section:{},'
                      'NoOptionError: {}'.format(option, section, e))
        if option_default_val:
            result = option_default_val
            conf.set(section, option, option_default_val)
            with open(file_path, 'w') as f:
                conf.write(f)
        else:
            result = None
    return result

.ini

[target]
HyperGate = HyperGate
MotionGear = MotionGear

[source]
vmware = VMware
openstack_ceph = Openstack_ceph
openstack+ceph = Openstack+Ceph
agent = Agent
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值