我有一个名为 Configuration.properties 的属性文件,其中包含:
path=/usr/bin
db=mysql
data_path=/temp
我需要读取此文件并在后续脚本中使用变量,如path、db 和data_path。 我可以使用 configParser 还是简单地读取文件并获取值来执行此操作。
提前致谢。
请您参考如下方法:
对于没有节头且被 [] 包围的配置文件 - 您会发现 ConfigParser.NoSectionError 异常被抛出。通过插入“假”节标题可以解决此问题 - 如 this answer 中所示.
如果文件很简单,如pcalcao's answer所述,您可以执行一些字符串操作来提取值。
这是一个代码片段,它返回配置文件中每个元素的键值对字典。
separator = "="
keys = {}
# I named your file conf and stored it
# in the same directory as the script
with open('conf') as f:
for line in f:
if separator in line:
# Find the name and value by splitting the string
name, value = line.split(separator, 1)
# Assign key value pair to dict
# strip() removes white space from the ends of strings
keys[name.strip()] = value.strip()
print(keys)
