擅长:python、mysql、java
<p>对于没有节头、被<code>[]</code>包围的配置文件,将引发<code>ConfigParser.NoSectionError</code>异常。可以通过插入“假”节头来解决此问题,如<a href="https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788">this answer</a>中所示。</p>
<p>如果文件很简单,如<a href="https://stackoverflow.com/a/27945127/2889798">pcalcao's answer</a>所述,您可以执行一些字符串操作来提取值。</p>
<p>下面是一个代码片段,它返回配置文件中每个元素的键值对字典。</p>
<pre><code>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)
</code></pre>