python 读取properties文件

Python 读取 properties 文件可以使用 configparser 模块,这个模块是 Python 的内置模块之一,可以很方便地读取和写入 INI 配置文件(包括 properties 文件)。

下面是一个简单的示例代码,展示了如何使用 configparser 模块读取 properties 文件:

import configparser
config = configparser.ConfigParser()
config.read('config.properties')
# 获取整个配置文件的 section 和 key-value 键值对
for section in config.sections():
    for key, value in config.items(section):
        print(f"{section}.{key}={value}")
# 获取指定 section 中的 key-value 键值对
jdbc_url = config.get('jdbc', 'url')
jdbc_username = config.get('jdbc', 'username')
jdbc_password = config.get('jdbc', 'password')
print(f"jdbc.url={jdbc_url}")
print(f"jdbc.username={jdbc_username}")
print(f"jdbc.password={jdbc_password}")

这段代码首先使用 configparser 模块创建一个 ConfigParser 对象,然后使用 read() 方法读取 properties 文件。之后可以使用 sections() 方法获取所有的 section,使用 items(section) 方法获取指定 section 中的 key-value 键值对。也可以使用 get(section, key) 方法获取指定 section 中的指定 key 的 value 值。

注意:上述示例代码中,config.properties 文件需要和 Python 脚本放在同一个目录下,或者指定文件的绝对路径。

希望这段代码可以帮助你读取 properties 文件。如果你还有其他问题,请随时继续提问。

  •