关闭ConfigParser打开的文件

15

我有以下内容:

config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()

如何关闭使用config.read打开的文件?

在我的情况下,当新的部分/数据添加到config.cfg文件时,我会更新我的wxtree小部件。但是它只更新一次,我怀疑这是因为config.read使文件处于打开状态。

顺便问一下,ConfigParserRawConfigParser之间的主要区别是什么?


1
来吧,文档是你的朋友:http://docs.python.org/library/configparser.html - Armandas
9
我已经阅读了它。找不到如何关闭它。至于ConfigParser和RawConfigParser之间的区别,我只看到一些方法上有所不同。 - sqram
4个回答

35

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() 中,供您使用 :)


15

使用readfp代替read:

with open('connections.cfg') as fp:
    config = ConfigParser()
    config.readfp(fp)
    sections = config.sections()

7
read_file 取代了 readfp。它们都是在 Python 配置文件解析模块(ConfigParser)中使用的方法。 - LukeDev

5
ConfigParserRawConfigParser之间的区别在于,ConfigParser会尝试“神奇地”扩展对其他配置变量的引用,例如:
x = 9000 %(y)s
y = spoons

在这种情况下,x将是9000个勺子,而y只是勺子。如果您需要此扩展功能,则文档建议您改用SafeConfigParser。我不知道两者之间的确切区别。如果您不需要扩展(您可能不需要),请使用RawConfigParser

4
为了验证您的猜测,使用 ConfigParser.readfp() 并自己处理文件的打开和关闭。在进行更改后调用 readfp
config = ConfigParser()
#...on each change
fp = open('connections.cfg')
config.readfp(fp)
fp.close()
sections = config.sections()

1
这个不行。readfp 接受一个文件对象作为参数,但是你的 read 只接受一个文件路径字符串。也许你在代码中只忘记了两个字符。 - bluish
1
感谢@bluish,18个月后发现的一个打字错误证明了它的相关性...链接和文本都没问题,现在代码示例已经修复。 - gimel
1
太好了!现在你应该得到一个赞。如果你删除了你的评论,我也会删除我的,这样答案就更清晰易读了 ;) - bluish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接