【问题标题】:Closing file opened by ConfigParser关闭由 ConfigParser 打开的文件
【发布时间】:2009-06-13 15:28:14
【问题描述】:

我有以下几点:

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

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

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

在我们讨论的时候,ConfigParserRawConfigParser 之间的主要区别是什么?

【问题讨论】:

  • 来吧,文档是你的朋友:docs.python.org/library/configparser.html
  • 我确实读过它。找不到如何关闭它。至于 ConfigParser 与 RawConfigParser,我看到的唯一区别是一些方法。

标签: python configparser


【解决方案1】:

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

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

阅读基本上意味着我也必须在完成后关闭这个资源,对吧?

我阅读了您在此处获得的答案,建议您自己打开文件并使用config.readfp(fp) 作为替代方案。我查看了documentation,发现确实没有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() 方法。如您所见,从底部算起的第 3 行,fp.close() 在任何情况下都会在使用后关闭打开的资源。这是提供给您的,已经包含在 ConfigParser.read() 的框中:)

【讨论】:

    【解决方案2】:

    使用readfp 代替阅读:

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

    【讨论】:

    【解决方案3】:

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

    x = 9000 %(y)s
    y = spoons
    

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 这不起作用。 readfp 接受文件对象作为参数,但您的 read 只接受带有文件路径的字符串。也许您只忘记了代码中的 2 个字符。
      • 感谢@bluish,18 个月后发现的拼写错误是相关性的证明……链接和文字都可以,现在代码示例已修复。
      • 太棒了!现在你值得一票。如果你删除你的评论,我会删除我的,这样答案会更清晰;)
      猜你喜欢
      • 2013-06-25
      • 1970-01-01
      • 2017-05-26
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      • 2015-01-11
      • 1970-01-01
      相关资源
      最近更新 更多