【发布时间】:2022-01-22 00:47:12
【问题描述】:
我有包含多行的属性文件和超过 1 行的一些值。像这样的:
first.key=\
Right,\
Side,\
Value
second.key=Second value
third.key=Third value
我想获取每个键的值。 我无法预处理文件,因此无法用三引号或其他任何内容括起来。 因此,例如,如果我想将文件中的每个键和值放在一个列表中,例如:
for line in file:
split = line.split('=')
然后获取key和value
key = split[0]
value = split[1]
print(key) -> first.key
print(value) -> \Right,\Side,\Value
for line in file:
while line.endswith('\\'):
line += next(file)
will give me TypeError: 'list' object is not an iterator
请记住,属性文件的每一行都是列表中的项目。 我能够为每一行提取键和值,但我正在努力如何使用多行值来做到这一点。如果上一行.endswith('\'),我可能应该将下一行附加到上一行,但我无法弄清楚。 编辑。 ['multiline.key=值的第一行\', '值的第二行\', '值的第三行\', '值的第四行\', '值的第五行\', 'another.key=某个值', 'some.key= 另一个值'] 我知道如何处理 'another.key=某个值', 'some.key=另一个值'
我想不通的是如何提取为单个值:
First line of the value\\', 'Second line of the value\\', 'Third
line of the value\\', 'Fourth line of the value\\', 'Fifth line of
the value\\'
对于 多行键
文件如下所示:
multiline.key=First line of the value\
Second line of the value\
Third line of the value\
Fourth line of the value\
Fifth line of the value\
another.key=Some value
some.key=Another value
预期结果:
1st key=multiline.key
1st value=First line of the value\Second line of the value\Third
line of the value\Fourth line of the value\Fifth line of the value\
2nd key=another.key
2nd value=Some value
3rd key=some.key
3rd value=Another value
【问题讨论】:
-
这能回答你的问题吗? parsing .properties file in Python
-
对于显示的文件,您的预期结果究竟是什么样的?目前尚不清楚您想要什么的示例,和/或您(错误地)得到的示例。
-
我想获取文件中的每个值,甚至是多行上的值。缺少哪些信息,我可以改进它吗?
-
在你最后显示的文件之后,显示(不仅仅是描述)你想要的输出。我认为这是三个字符串的列表?还是一个字典,其值是那些字符串?
-
谢谢。列表的使用似乎很奇怪,但至少它相当清楚你想要什么,如果不是为什么。你熟悉 Python dictionaries 吗?这将是表示键和值的更自然的选择。
标签: python extract key-value multiline properties-file