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
read()
これはConfigParser.py ソース コードからの実際のメソッドです。ご覧のとおり、下から 3 行目は、fp.close()
使用後に開いているリソースを閉じます。これは提供され、すでに ConfigParser.read() のボックスに含まれています :)