python - 从 python 中的 configparser 读取时,如何让缩进包含在多行值中?

标签 python ini configparser

我有这样的配置文件:

[main]
key_one   =
  hello
    this
      is
        indented

但是当我像这样使用 python 中的 configparser 库读取它时:

import configparser
cfg = configparser.ConfigParser()
cfg.read("path/to/file.ini")
print(cfg["main"]["key_one"])

打印出来:

hello
this
is
indented

我试过使用制表符,每个缩进超过两个空格,但似乎没有任何效果。如何让 configparser 识别缩进?

最佳答案

解析器本身总是会去除前导空格;据我所知,没有(推荐的)方法可以改变它。

解决方法是使用非空白字符来指示格式化文本的开头,然后在读取文件后将其删除。例如,

[main]
key_one   =| hello
           |   this
           |     is
           |       indented

然后在你的脚本中

import configparser
import re

cfg = configparser.ConfigParser()
cfg.read("tmp.ini")
t = cfg["main"]["key_one"]
t = re.sub("^\|", "", t, flags=re.MULTILINE)
print(t)

产生

$ python3 tmp.py
 hello
   this
     is
       indented

该值紧接在 = 之后开始(我将您的第一行向上移动,假设您真的不希望该值以换行符开头)。解析器保留 | 之后的任何非尾随空白作为每行的第一个非空白字符。 re.sub 将从每一行中删除初始的 |,留下所需的缩进多行字符串作为结果。

关于python - 从 python 中的 configparser 读取时,如何让缩进包含在多行值中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60874524/

相关文章:

php - 如何增加php的最大执行时间

delphi - TIniFile.WriteBinaryStream 创建异常

python - Python 3 中的 configparser 中的 read 和 read_file 有什么区别?

python - 如何使用 Python ConfigParser 从配置文件中读取换行符

python - 使用 jinja2 仅显示 URL 域的最佳方式

python - 如何将反锯齿函数拟合到曲线或绘图?

c++ - 从 Lua 中提取变量到 C++

python - 使用 python "ConfigParser"编辑 ini 文件会将所有 ini 条目替换为较低的键

python - 在 Python 中使用 BeautifulSoup 查找 html 标签

python - 多索引答案 Python 3