gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:43:40 29 4
gpt4 key购买 nike

我有一个 .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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com