【问题标题】:configparser does not show sectionsconfigparser 不显示部分
【发布时间】:2019-11-20 08:59:17
【问题描述】:

我在 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()

返回

[]

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

【问题讨论】:

  • 仅供参考,with 语句将为您关闭它,因此无需分配给变量文件。只需使用with open("...", "a") as f: 并删除close()
  • 从文档中,config.read 接受 文件名,而不是文件描述符对象。 IE。 config.read("ini/inifile.ini")。如果要使用文件描述符对象,请改用config.read_file(f)
  • @alkasm 谢谢!您可以将其写为关闭问题的答案

标签: python configparser


【解决方案1】:

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

read(filenames, encoding=None)

尝试读取和解析文件名的可迭代,返回成功解析的文件名列表。

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

如果不存在任何命名文件,则 ConfigParser 实例将包含一个空数据集。 ...

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

无论如何,您应该将文件名直接传递给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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多