python - 如何使用 python configparser 读取缩进部分

标签 python configparser

我尝试使用 python configparser 读取以下配置文件:

# test.conf
[section]
a = 0.3

        [subsection]
        b = 123
# main.py

import configparser
conf = configparser.ConfigParser()
conf.read("./test.conf")
a = conf['section']['a']
print(a)

输出:

0.3

[subsection]
b = 123

如果我删除缩进,a 就会被正确读取。

如何使用 python configparser 正确读取带有缩进的配置文件?

根据文档,它应该可以工作:
https://docs.python.org/3.8/library/configparser.html#supported-ini-file-structure

我用的是python 3.7.6

最佳答案

在 python 错误跟踪器中提出错误后,我找到了一种阅读指定小节的方法。 将 empty_lines_in_values=False 添加到您的代码中。

错误跟踪器链接:https://bugs.python.org/issue41379

import configparser
conf = configparser.ConfigParser(empty_lines_in_values=False)
conf.read("./test.conf")
a = conf['section']['a']
print(a)

输出:

hello

关于python - 如何使用 python configparser 读取缩进部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62833787/

相关文章:

python - 如何切换 bool argparse 选项?

python - 在 Python 中处理(可能的)可选参数

python 2.7 : "unresolved import: ConfigParser"

python - Django 多对多和管理

python - 使用循环在 .ini 文件中分配已知数量的变量

python 3 configparser.read() 在给定不存在的文件时不会引发异常

python - 重新格式化列表中的字符串 - Python

python - 除以零错误输入到Tkinter消息中供计算器使用

Python 控制台不允许我编写新的代码行。 PyCharm

python - 删除 Numpy 数组中的 NaN 和 Infs