【发布时间】:2014-10-20 18:44:04
【问题描述】:
所以我想首先说我一直在寻找这个问题的答案,但找不到任何有用的东西。我还查看了 Python 的文档,但没有找到有用的东西。我的最后一个问题有点懒惰并收到了负面反馈,所以我正在尽我所能在这里提出一个简单而直接的问题。一如既往,提前感谢您的帮助!
那么,谁能解释一下我在使用 Python 的 ConfigParser 时遇到的这种奇怪行为。我有两个不同的配置文件,每个都有一个Section 1。这两个文件具有不同数量的选项,但选项数量较少的文件将被覆盖。这是代码和输出:
第一个配置文件:test1.ini
[Section 1]
Option 1 : One
Option 2 : Two
Option 3 : None
Option 4 : Four
第二个配置文件:test2.ini
[Section 1]
Option 1 : One
Option 2 : None
Option 3 : Three
读取配置文件的驱动程序
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
def ParseThis(file, section):
parser.read(file)
for option in parser.options(section):
print "\t" + option
try:
if parser.get(section, option) != 'None':
print option + ": " + parser.get(section, option)
else:
print option + ": Option doesn't exist"
except:
print option + ": Something went wrong"
print "First File:"
print "Section 1"
ParseThis('test2.ini', 'Section 1')
print "\n"
print "Second File: "
print "Section 1"
ParseThis('test1.ini', 'Section 1')
print "\n"
print "First File: "
print "Section 1"
ParseThis('test2.ini', 'Section 1')
这是我得到的输出,没有任何意义。
First File:
Section 1
option 1
option 1: One
option 2
option 2: Option doesn't exist
option 3
option 3: Three
Second File:
Section 1
option 1
option 1: One
option 2
option 2: Two
option 3
option 3: Option doesn't exist
option 4
option 4: Four
First File:
Section 1
option 1
option 1: One
option 2
option 2: Option doesn't exist
option 3
option 3: Three
option 4 <== why this line?
option 4: Four <== why this line?
【问题讨论】:
标签: python configparser