python - 解析和使用 .properties 文件中使用 PYTHON 定义的属性

标签 python parsing properties config

我有一个 .properties 文件,其中存储了一些我想从 python 文件中使用的键和值。

我的 test.properties 文件是这样的:

attribute1=username
attribute2=address
attribute3=class

我想从 python 文件访问这些属性,这样当我执行以下操作时:

attribute1 = "tom123"
attribute2 = "5 Smith Street"
attribute3 = "402"

但现在我想知道如何在 python 中导入 config.properties 文件并开始使用定义的属性。 任何帮助将不胜感激,谢谢。

最佳答案

你可以像这样在Python字典中加载你的配置文件:

config = {}

with open('config.properties', 'r', ) as f:
    for line in f.readlines():
        line = line.strip()  # removes the newline characters
        parts = line.split("=")  # creates a (key, value) tuple
        key = parts[0]
        value = parts[1]
        config[key] = value

attribute1 = config['attribute1']
attribute2 = config['attribute2']
attribute3 = config['attribute3']

关于python - 解析和使用 .properties 文件中使用 PYTHON 定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41949432/

相关文章:

python - 使用长正则表达式公式进行自由文本解析导致错误 : multiple repeat in python? 包含屏幕截图

java - JSONException - 将字符串解析为 JSONArray

Python:Pandas 数据框列评估

python - 优步 API : request_ride with sandbox_mode=True is throwing error message

c++ - Boost::spirit(经典)基元与自定义解析器

.net - 多个属性的线程安全模式

vb.net - 我应该使用私有(private)变量还是属性

java - 使用 Spring 自动从属性文件连接多个数组

python - 从子模块隐式导入

python - 更新指向 settings.AUTH_USER_MODEL 的关系