杰瑞科技汇

python读取properties

在 Python 中读取 .properties 文件(Java 配置文件格式)可以使用标准库 configparser(推荐)或第三方库 python-properties,以下是两种方法的详细说明:

python读取properties-图1
(图片来源网络,侵删)

方法1:使用标准库 configparser(推荐)

configparser 是 Python 内置的库,用于解析类似 Windows INI 格式的配置文件,但也能处理简单的 .properties 文件。

示例代码

from configparser import ConfigParser
# 创建 ConfigParser 对象
config = ConfigParser()
# 读取 properties 文件(需指定 encoding,避免中文乱码)
config.read('config.properties', encoding='utf-8')
# 获取配置值
host = config.get('database', 'host')  # 区分大小写,section 和 key 都需匹配
port = config.getint('database', 'port')  # 自动转换为 int
username = config.get('database', 'username')
print(f"Host: {host}, Port: {port}, Username: {username}")

注意事项

  1. 文件格式要求

    • .properties 文件需要转换为 [section] 格式:

      # 原始 properties 格式
      database.host=localhost
      database.port=3306
      # 需要手动调整为 ConfigParser 格式
      [database]
      host = localhost
      port = 3306
  2. 大小写敏感

    python读取properties-图2
    (图片来源网络,侵删)
    • configparser 默认不区分大小写,但通过 optionxform=str 可以区分:
      config = ConfigParser()
      config.optionxform = str  # 保持原始大小写

方法2:使用第三方库 python-properties

如果需要严格兼容 Java 的 .properties 格式(无需转换 [section]),可以使用第三方库。

安装

pip install python-properties

示例代码

from javaobj import properties  # 实际库名可能是 properties-py 或其他
# 直接读取 properties 文件
props = properties.Properties()
props.load(open('config.properties', 'rb'))  # 二进制模式读取
# 获取配置值
host = props['database.host']  # 直接通过 key 访问
port = int(props['database.port'])
username = props['database.username']
print(f"Host: {host}, Port: {port}, Username: {username}")

注意事项

  • 中文编码:确保文件以 UTF-8 编码保存,或指定编码:
    props.load(open('config.properties', 'r', encoding='utf-8'))
  • 依赖问题:某些第三方库可能依赖 Java 环境,建议优先使用 configparser

方法3:手动解析(简单场景)

如果文件格式简单(无嵌套结构),可以直接逐行解析:

def parse_properties(file_path):
    props = {}
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):  # 跳过空行和注释
                key, value = line.split('=', 1)
                props[key.strip()] = value.strip()
    return props
props = parse_properties('config.properties')
print(props['database.host'])

方法 优点 缺点
configparser Python 内置,无需安装 需要调整文件格式为 [section]
python-properties 兼容 Java 格式,无需转换 需要安装第三方库
手动解析 灵活,适合简单文件 需自行处理复杂格式

推荐选择

  • 如果文件可控,优先用 configparser
  • 如果必须兼容原始 .properties 格式,用 python-properties
  • 简单场景可直接手动解析。
分享:
扫描分享到社交APP
上一篇
下一篇