[英]How can I get indentation to be included in a multiline value when read from configparser in python?
I have some config file like this:我有一些这样的配置文件:
[main]
key_one =
hello
this
is
indented
But when I read it using the configparser library in python like so:但是当我像这样使用 python 中的 configparser 库读取它时:
import configparser
cfg = configparser.ConfigParser()
cfg.read("path/to/file.ini")
print(cfg["main"]["key_one"])
Prints out:打印出来:
hello
this
is
indented
I've tried using tabs, more than two spaces per indent, nothing seems to work.我试过使用制表符,每个缩进两个以上的空格,似乎没有任何效果。 How can I get configparser to recognize indents?
如何让 configparser 识别缩进?
The parser itself will always strip leading whitespace;解析器本身总是会去除前导空格; as far as I can tell, there is no (recommended) way to change that.
据我所知,没有(推荐的)方法可以改变它。
A workaround is to use a non-whitespace character to indicate the beginning of your formatted text, then strip that after reading the file.一种解决方法是使用非空白字符来指示格式化文本的开头,然后在读取文件后将其删除。 For example,
例如,
[main]
key_one =| hello
| this
| is
| indented
Then in your script然后在你的脚本中
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)
which produces产生
$ python3 tmp.py
hello
this
is
indented
The value starts immediately after the =
(I moved your first line up, assuming you didn't really want the value to start with a newline character).该值在
=
之后立即开始(我将您的第一行向上移动,假设您真的不希望该值以换行符开头)。 The parser preserves any non-trailing whitespace after |
解析器保留
|
之后的任何非尾随空格|
, as the first non-whitespace character on each line. , 作为每行的第一个非空白字符。
re.sub
will remove the initial |
re.sub
将删除初始|
from each line, leaving the desired indented multi-line string as the result.从每一行,留下所需的缩进多行字符串作为结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.