Closing file opened by ConfigParser

后端 未结 4 1202
北恋
北恋 2020-12-31 08:35

I have the following:

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

How can I close the file opened

4条回答
  •  -上瘾入骨i
    2020-12-31 09:15

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

    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 documentation and saw that indeed there is no ConfigParser.close(). So I researched a little more and read the ConfigParser code implementation itself:

    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() :)

提交回复
热议问题