python 关闭由 ConfigParser 打开的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/990867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:13:17  来源:igfitidea点击:

Closing file opened by ConfigParser

pythonconfigparser

提问by sqram

I have the following:

我有以下几点:

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

How can I close the file opened with config.read?

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

In my case, as new sections/data are added to the config.cfgfile, I update my wxtree widget. However, it only updates once, and I suspect it's because config.readleaves the file open.

就我而言,随着新的部分/数据添加到config.cfg文件中,我更新了 wxtree 小部件。但是,它只更新一次,我怀疑这是因为config.read文件保持打开状态。

And while we are at it, what is the main difference between ConfigParserand RawConfigParser?

当我们讨论它时,ConfigParser和之间的主要区别是RawConfigParser什么?

采纳答案by Nicolas Dumazet

Use readfpinstead of read:

使用readfp而不是 read:

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

回答by user1555863

ConfigParser.read(filenames)actually takes care of that for you.

ConfigParser.read(filenames)实际上会为您解决这个问题。

While coding I have encountered this issue and found myself asking myself the very same question:

在编码时,我遇到了这个问题,并发现自己问自己同样的问题:

Reading basically means I also have to close this resource after I'm done with it, right?

阅读基本上意味着我还必须在完成后关闭此资源,对吗?

I read the answer you got here suggesting to open the file yourself and use config.readfp(fp)as an alternative. I looked at the documentationand saw that indeed there is no ConfigParser.close(). So I researched a little more and read the ConfigParser code implementation itself:

我阅读了您在此处获得的答案,建议您自己打开文件并将其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

This is the actual read()method from ConfigParser.py source code. As you can see, 3rd line from the bottom, fp.close()closes the opened resource after its usage in any case. This is offered to you, already included in the box with ConfigParser.read() :)

这是read()来自 ConfigParser.py 源代码的实际方法。如您所见,从底部算起的第三行在fp.close()任何情况下都会在使用后关闭打开的资源。这是提供给您的,已包含在带有 ConfigParser.read() 的框中:)

回答by Paul Fisher

The difference between ConfigParserand RawConfigParseris that ConfigParserwill attempt to "magically" expand references to other config variables, like so:

ConfigParser和之间的区别在于RawConfigParserConfigParser它将尝试“神奇地”扩展对其他配置变量的引用,如下所示:

x = 9000 %(y)s
y = spoons

In this case, xwill be 9000 spoons, and ywill just be spoons. If you need this expansion feature, the docs recommend that you instead use SafeConfigParser. I don't know what exatly the difference between the two is. If you don't need the expansion (you probably don't) just need RawConfigParser.

在这种情况下,x将是9000 spoons,并且y只是spoons。如果您需要此扩展功能,文档建议您改用SafeConfigParser. 我不知道这两者之间的区别是什么。如果您不需要扩展(您可能不需要)只需要RawConfigParser.

回答by gimel

To test your suspicion, use ConfigParser.readfp()and handle opening and closing of the file by yourself. Make the readfpcall after the changes are made.

要测试您的怀疑,请使用ConfigParser.readfp()自行处理文件的打开和关闭。readfp进行更改后进行调用。

config = ConfigParser()
#...on each change
fp = open('connections.cfg')
config.readfp(fp)
fp.close()
sections = config.sections()