Python 读取配置文件config.ini

本文介绍了如何在Python中使用configparser模块来读取、写入和管理ini配置文件,包括创建配置文件、读取配置项、获取配置内容等基本操作,适用于项目中的配置管理。

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


前言

在项目制的工作中往往会用到配置文件,这样可以灵活配置和切换,ini最常见一种配置文件类型,其使用python自带的configparser模块实现配置文件的写入、更新、删除、读取等操作。


一、创建配置文件config.ini

[Mock]
mock_ip = 127.0.0.1
mock_port = 9991

[Log]
log_name = mock.log
log_level = info
cache_name = cache.txt

[Interface]
interface_ip = 127.0.0.1
interface_port = 19991

ini结构:
片段(section)对应 [Mock]
选项(option)对应 mock_ip,相当于key
值(value)对应127.0.0.1,相当于value

二、使用步骤

1.安装库并引入库

pip install configparser

import configparser
import os

2.读取配置文件

# 读取配置文件 
def read_config():
    root_dir = os.path.dirname(os.path.dirname(__file__))  # # 获取当前文件所在目录
    config_dir = os.path.join(root_dir, 'config', 'config.ini')  # 组装config.ini路径,也可以直接写配置文件的具体路径,不用自动获取
    cf = configparser.ConfigParser()
    cf.read(config_dir, encoding="utf-8")  # 读取config.ini
    return cf

3. 获取配置文件的内容

if __name__ == '__main__':
	cf = read_config()
    mock_ip = cf.get('Mock', 'mock_ip')
    mock_port = cf.getint('Mock', 'mock_port') # 注意端口要用getint方法获取
    print(mock_ip)
    print(mock_port)

总结

	# 读取配置文件 常用的方法介绍
	cf.read(filename)    # 读取文件,返回filename的list

    cf.sections()    # 获取配置文件中所有sections的list

    cf.options(section)    # 获取指定section的键值list

    cf.items(section)    # 获取指定section下所有的键值对list

    cf.get(section, key)    # 获取指定section下指定key的value值, 返回str

    cf.getint(section, key)    # 获取指定sections下指定key的value值, 返回int

    cf.getfloat(section, key)    # 获取指定sections下指定key的value值, 返回float

    cf.getboolean(section, key)    # 获取指定sections下指定key的value值, 返回boolean

    cf.has_section(section)    # 获取是否包含某个section,返回boolean

    cf.has_option(section,key)    # 获取是否包含某个section的某个键,返回boolean
# 写入配置文件 常用方法介绍
cf = configparser.ConfigParser()    # 实例化对象

cf.read(self.filename)    # 读取文件,如果是重新写入,覆盖原有内容不需要读取 

cf.add_section(section)    # 添加sections值

cf.set(section, option, value)    # 在指定的sections中添加键值对

cf.remove_section(section)    # 移除sections, 需要先cf.read(filename)

cf.remove_option(section, option)    # 移除指定sections下的options, 需要先cf.read(filename)
# 样例介绍
class WriteConfig():
    """写入config文件"""
    def __init__(self, filename, filepath=r"D:\python_file\boke\config"):
        self.filename = filename
        os.chdir(filepath)
        self.cf = configparser.ConfigParser()
        self.cf.read(self.filename)    # 如果修改,则必须读原文件

    def _with_file(self):
        # write to file
        with open(self.filename, "w+") as f:
            self.cf.write(f)

    def add_section(self, section):
        # 写入section值
        self.cf.add_section(section)
        self._with_file()

    def set_options(self,section, option, value=None):
        """写入option值"""
        self.cf.set(section, option, value)
        self._with_file()

    def remove_section(self, section):
        """移除section值"""
        self.cf.remove_section(section)
        self._with_file()

    def remove_option(self, section, option):
        """移除option值"""
        self.cf.remove_option(section, option)
        self._with_file()
<think>我们被要求用Python编写和读取config.ini文件。根据引用[2]和引用[3],我们可以使用Python内置的configparser模块来处理INI文件。步骤:1.导入configparser模块2.创建ConfigParser对象3.读取INI文件:使用read()方法4.获取配置:通过section和option来获取值5.写入配置:设置section和option的值,然后写入文件下面分别给出读取和写入的示例代码。假设我们有一个config.ini文件,内容如下:```[database]host=localhostport=3306user=rootpassword=123456[app]name=MyApplicationdebug=True```读取示例:我们可以读取特定section下的option的值。写入示例:我们可以修改现有的值,或者添加新的section和option,然后写回到文件。注意:在写入时,如果文件不存在,ConfigParser会创建新的文件;如果section不存在,我们也可以先添加section,再添加option。下面提供两个函数:一个用于读取配置,一个用于写入配置。</think>### Python 编写和读取 config.ini 文件示例 #### 1. **创建 config.ini 文件** ```python import configparser def create_config(): config = configparser.ConfigParser() # 添加配置项 config['DATABASE'] = { 'host': 'localhost', 'port': '3306', 'user': 'admin', 'password': 'secret' } config['APP_SETTINGS'] = { 'debug': 'True', 'max_connections': '100', 'timeout': '30' } # 写入文件 with open('config.ini', 'w') as configfile: config.write(configfile) create_config() ``` *执行后生成 `config.ini` 文件内容:* ```ini [DATABASE] host = localhost port = 3306 user = admin password = secret [APP_SETTINGS] debug = True max_connections = 100 timeout = 30 ``` #### 2. **读取 config.ini 文件** ```python import configparser def read_config(): config = configparser.ConfigParser() config.read('config.ini') # 获取特定值 db_host = config.get('DATABASE', 'host') timeout = config.getint('APP_SETTINGS', 'timeout') # 自动转换为整数 print(f"数据库地址: {db_host}") print(f"超时设置: {timeout}秒") # 遍历所有配置 for section in config.sections(): print(f"\n[{section}]") for key, value in config.items(section): print(f"{key} = {value}") read_config() ``` #### 3. **修改配置值** ```python def update_config(): config = configparser.ConfigParser() config.read('config.ini') # 修改现有值 config.set('APP_SETTINGS', 'timeout', '60') # 添加新配置项 if not config.has_section('LOGGING'): config.add_section('LOGGING') config.set('LOGGING', 'level', 'INFO') # 保存修改 with open('config.ini', 'w') as configfile: config.write(configfile) update_config() ``` *修改后的 `config.ini` 新增内容:* ```ini [LOGGING] level = INFO ``` #### 关键点说明: 1. **数据类型处理**: - 使用 `getint()`, `getfloat()`, `getboolean()` 自动转换类型 - 默认返回字符串类型 2. **错误处理**: ```python try: value = config.get('SECTION', 'key') except (configparser.NoSectionError, configparser.NoOptionError): value = 'default' ``` 3. **文件路径**: - 建议使用绝对路径:`config.read('/path/to/config.ini')` - 或结合 `os.path` 动态获取路径 #### 实际应用场景: 1. 数据库连接参数管理[^3] 2. 应用程序运行时配置[^2] 3. 自动化测试参数存储[^4] 4. 多环境配置切换(开发/生产) > 注意:敏感信息(如密码)应避免明文存储,可使用环境变量或加密模块增强安全性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值