Python configparser不显示节

Python configparser不显示节,python,configparser,Python,Configparser,我将节及其值添加到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

我将节及其值添加到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()
返回

[]

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

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

读取
文件名,encoding=None

尝试读取和分析文件名的列表,返回已成功分析的文件名列表

如果文件名是字符串、字节对象或类似路径的对象,则将其视为单个文件名

如果命名文件均不存在,ConfigParser实例将包含一个空数据集

文件对象是字符串的一个iterable,因此基本上配置解析器试图将文件中的每个字符串作为文件名读取。这有点有趣和愚蠢,因为如果你给它传递了一个包含实际配置文件名的文件,它就会工作

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

或者,如果您想使用文件描述符对象,只需使用
config.read\u file(f)
。有关更多信息,请阅读


另一方面,您正在复制上下文管理器正在做的一些工作,但没有任何收益。您可以将
块一起使用,而无需先显式创建对象或在之后关闭对象(它将自动关闭)。保持简单:

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

仅供参考,
with
语句将为您关闭它,因此无需分配给变量文件。只需使用带有open(“…”,“a”)的
作为f:
并删除
close()
。从文档中,
config.read
接受文件名,而不是文件描述符对象。即
config.read(“ini/inifile.ini”)
。如果要使用文件描述符对象,请改用
config.read\u file(f)
@alkasm谢谢!你可以把它写下来作为结束问题的答案