关闭ConfigParser打开的文件

sqr*_*ram 12 python configparser

我有以下内容:

config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()
Run Code Online (Sandbox Code Playgroud)

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

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

虽然我们在这里,但ConfigParser和之间的主要区别是RawConfigParser什么?

use*_*863 24

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
Run Code Online (Sandbox Code Playgroud)

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


Nic*_*zet 12

使用readfp而不是read:

with open('connections.cfg') as fp:
    config = ConfigParser()
    config.readfp(fp)
    sections = config.sections()
Run Code Online (Sandbox Code Playgroud)

  • [read_file](https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read_file)立即替换为readfp (3认同)

Pau*_*her 5

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

x = 9000 %(y)s
y = spoons
Run Code Online (Sandbox Code Playgroud)

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