关闭ConfigParser打开的文件
我有以下内容:
config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()
我该如何关闭用 config.read
打开的文件呢?
在我的情况下,随着新的部分/数据被添加到 config.cfg
文件中,我会更新我的 wxtree 小部件。但是,它只更新了一次,我怀疑这是因为 config.read
让文件保持打开状态。
顺便问一下,ConfigParser
和 RawConfigParser
之间的主要区别是什么?
4 个回答
ConfigParser
和RawConfigParser
之间的区别在于,ConfigParser
会尝试“神奇地”展开对其他配置变量的引用,像这样:
x = 9000 %(y)s
y = spoons
在这个例子中,x
的值会变成9000 spoons
,而y
的值则只是spoons
。如果你需要这种展开的功能,文档建议你使用SafeConfigParser
。我不太清楚这两者之间的具体区别。如果你不需要这种展开功能(你可能不需要),那么只需使用RawConfigParser
就可以了。
ConfigParser.read(filenames)
其实已经为你处理好了这个问题。
在编程的时候,我也遇到过这个问题,心里也在想:
读文件的时候,我是不是也得在用完之后把这个资源关掉呢,对吧?
我看过你在这里得到的回答,建议你自己打开文件,然后用 config.readfp(fp)
作为替代。我查了一下文档,发现确实没有 ConfigParser.close()
这个方法。所以我又多查了一些,甚至看了 ConfigParser 的代码实现:
def read(self, filenames):
"""Read and parse a filename or a list of filenames.
Files that cannot be opened are silently ignored; this is
designed so that you can specify a list of potential
configuration file locations (e.g. current directory, user's
home directory, systemwide directory), and all existing
configuration files in the list will be read. A single
filename may also be given.
Return list of successfully read files.
"""
if isinstance(filenames, basestring):
filenames = [filenames]
read_ok = []
for filename in filenames:
try:
fp = open(filename)
except IOError:
continue
self._read(fp, filename)
fp.close()
read_ok.append(filename)
return read_ok
这是 ConfigParser.py 源代码中的实际 read()
方法。你可以看到,在倒数第三行,fp.close()
在使用完资源后会自动关闭它。所以这个功能其实已经包含在 ConfigParser.read()
里了,完全不需要你额外去操心 :)
使用 readfp 方法,而不是 read 方法:
with open('connections.cfg') as fp:
config = ConfigParser()
config.readfp(fp)
sections = config.sections()