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