以下是 Python 读取各种配置文件格式的示例代码:
1. INI 格式
python
import configparser |
# 读取文件 |
config = configparser.ConfigParser() |
config.read('config.ini') |
# 获取值 |
db_host = config.get('database', 'host') |
db_port = config.getint('database', 'port') # 自动转换为整数 |
print(f"Host: {db_host}, Port: {db_port}") |
2. JSON 格式
python
import json |
# 读取文件 |
with open('config.json', 'r') as f: |
config = json.load(f) |
# 获取值 |
db_host = config['database']['host'] |
db_port = config['database']['port'] |
print(f"Host: {db_host}, Port: {db_port}") |
3. YAML 格式
python
import yaml # 需安装 PyYAML: pip install pyyaml |
# 读取文件 |
with open('config.yaml', 'r') as f: |
config = yaml.safe_load(f) |
# 获取值 |
db_host = config['database']['host'] |
db_port = config['database']['port'] |
print(f"Host: {db_host}, Port: {db_port}") |
4. TOML 格式
python
import tomlkit # 需安装 tomlkit: pip install tomlkit |
# 读取文件 |
with open('config.toml', 'r') as f: |
config = tomlkit.parse(f.read()) |
# 获取值 |
db_host = config['database']['host'] |
db_port = config['database']['port'] |
print(f"Host: {db_host}, Port: {db_port}") |
5. 环境变量
python
import os |
# 直接读取环境变量 |
db_host = os.getenv('DB_HOST') |
db_port = int(os.getenv('DB_PORT', '3306')) # 默认值 3306 |
print(f"Host: {db_host}, Port: {db_port}") |
6. XML 格式
python
import xml.etree.ElementTree as ET |
# 解析 XML |
tree = ET.parse('config.xml') |
root = tree.getroot() |
# 提取值 |
db_host = root.find('host').text |
db_port = int(root.find('port').text) |
print(f"Host: {db_host}, Port: {db_port}") |
7. Python 脚本(.py 文件)
python
# config.py |
DATABASE = { |
"host": "localhost", |
"port": 3306, |
"user": "admin", |
"password": "secret" |
} |
# 主程序 |
from config import DATABASE |
print(f"Host: {DATABASE['host']}, Port: {DATABASE['port']}") |
8. .env 文件
python
from dotenv import load_dotenv # 需安装 python-dotenv: pip install python-dotenv |
import os |
# 加载 .env 文件 |
load_dotenv() |
# 读取值 |
db_host = os.getenv('DB_HOST') |
db_port = int(os.getenv('DB_PORT')) |
print(f"Host: {db_host}, Port: {db_port}") |
关键注意事项:
- 安装依赖:YAML、TOML、.env 等格式需要额外安装库。
- 路径问题:确保文件路径正确(相对路径或绝对路径)。
- 类型安全:部分格式(如 JSON/YAML)返回字符串,需手动转换类型。
- 安全性:敏感信息(如密码)建议使用环境变量或
.env
文件,并添加到.gitignore
。