configparser 不显示部分

configparser does not show sections

我在 ini 文件中添加了部分及其值,但 configparser 不想打印我总共有哪些部分。我做了什么:

import configparser
import os


# creating path
current_path = os.getcwd()
path = 'ini'
try:
    os.mkdir(path)
except OSError:
    print("Creation of the directory %s failed" % path)


# add section and its values
config = configparser.ConfigParser()
config['section-1'] = {'somekey' : 'somevalue'}
file = open(f'ini/inifile.ini', 'a')
with file as f:
    config.write(f)
file.close()

# get sections
config = configparser.ConfigParser()
file = open(f'ini/inifile.ini')
with file as f:
    config.read(f)
    print(config.sections())
file.close()

returns

[]

类似的代码是 in the documentation,但不起作用。我做错了什么以及如何解决这个问题?

the docs 开始,config.read() 接受一个 文件名 (或它们的列表),而不是文件描述符对象:

read(filenames, encoding=None)

Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed.

If filenames is a string, a bytes object or a path-like object, it is treated as a single filename. ...

If none of the named files exist, the ConfigParser instance will contain an empty dataset. ...

一个文件对象是一个可迭代的字符串,所以基本上配置解析器试图读取文件中的每个字符串作为文件名。这有点有趣和愚蠢,因为如果您向它传递一个包含实际配置文件名的文件...它就会起作用。

无论如何,您应该将文件名直接传递给 config.read(),即 config.read("ini/inifile.ini")

或者,如果您想改用文件描述符对象,只需使用 config.read_file(f)。阅读 docs for read_file() 了解更多信息。


顺便说一句,您正在重复上下文管理器所做的一些工作而没有任何收获。您可以使用 with 块,而无需首先显式创建对象或之后关闭它(它将自动关闭)。保持简单:

with open("path/to/file.txt") as f:
    do_stuff_with_file(f)