如何写python的配置文件

  • Post category:Python

写 Python 的配置文件可以采用常见的文本格式如 INI 和 YAML,也可以直接使用 Python 代码实现。下面就来介绍如何使用 INI 格式和 Python 代码实现配置文件。

使用 INI 格式实现配置文件

INI 格式是一种常见的配置文件格式,使用上相对简单。基本结构包括节(Section)和键值对(Key-Value),每个节里面可以包含多个键值对。

安装 ConfigParser

在 Python 中读取和写入 INI 文件需要使用 ConfigParser 库。如果你使用的是 Python 2.x 版本,则需要安装 ConfigParser;如果使用的是 Python 3.x 版本,则需要安装 configparser。

安装命令如下:

# Python 2.x 版本
pip install ConfigParser

# Python 3.x 版本
pip install configparser

写入 INI 配置文件

下面就是 INI 配置文件的一个例子:

[mysql]
host=localhost
user=root
password=123456
database=test

这里我们创建了一个 mysql 节,包含了 host、user、password 和 database 四个键值对。

写入上述配置文件的 Python 代码如下:

import ConfigParser # Python 2.x
# import configparser # Python 3.x

config = ConfigParser.ConfigParser()
config.add_section('mysql')
config.set('mysql', 'host', 'localhost')
config.set('mysql', 'user', 'root')
config.set('mysql', 'password', '123456')
config.set('mysql', 'database', 'test')

with open('config.ini', 'w') as f:
    config.write(f)

在代码中,我们首先导入 ConfigParser 库,然后创建了一个 ConfigParser 实例,接着添加了一个 mysql 节和四个键值对,最后将配置信息写入 config.ini 文件中。

读取 INI 配置文件

读取 INI 文件的 Python 代码如下:

import ConfigParser # Python 2.x
# import configparser # Python 3.x

config = ConfigParser.ConfigParser()
config.read('config.ini')

host = config.get('mysql', 'host')
user = config.get('mysql', 'user')
password = config.get('mysql', 'password')
database = config.get('mysql', 'database')

print(host, user, password, database)

在代码中,我们首先导入 ConfigParser 库,然后创建了一个 ConfigParser 实例,接着读取了 config.ini 文件中的配置信息。最后,我们使用 get 方法获取了 mysql 节中的 host、user、password 和 database 四个键值对,并打印输出。

使用 Python 代码实现配置文件

我们也可以使用 Python 代码实现配置文件的读写,这种方式在一些特殊场景下会比较方便。

写入 Python 配置文件

下面是使用 Python 代码实现的一个例子:

config = {
    'mysql': {
        'host': 'localhost',
        'user': 'root',
        'password': '123456',
        'database': 'test'
    },

    'email': {
        'smtp_server': 'smtp.example.com',
        'smtp_port': 587,
        'from_addr': 'sender@example.com',
        'password': '123456',
        'to_addr': ['receiver1@example.com', 'receiver2@example.com']
    }
}

import json

with open('config.py', 'w') as f:
    f.write('config = ' + json.dumps(config))

在代码中,我们使用一个字典来存储配置信息,并使用 json.dumps 方法将其转为 JSON 字符串,最后将其写入 config.py 文件中。

读取 Python 配置文件

读取 Python 配置文件的 Python 代码如下:

from config import config

host = config['mysql']['host']
user = config['mysql']['user']
password = config['mysql']['password']
database = config['mysql']['database']

print(host, user, password, database)

smtp_server = config['email']['smtp_server']
smtp_port = config['email']['smtp_port']
from_addr = config['email']['from_addr']
password = config['email']['password']
to_addr = config['email']['to_addr']

print(smtp_server, smtp_port, from_addr, password, to_addr)

在代码中,我们首先从 config.py 文件中导入 config 配置字典,然后使用字典的索引方式获取 mysql、email 等节里面的键值对。

以上就是使用 INI 格式和 Python 代码实现配置文件的详细攻略。如果在实际开发过程中还有什么疑问,请随时提问。