gpt4 book ai didi

python - 如何在 python 中读取多行 .properties 文件

转载 作者:太空狗 更新时间:2023-10-30 02:34:51 24 4
gpt4 key购买 nike

我正在尝试读取 java 多行 i18n 属性文件。有这样的行:

messages.welcome=Hello\
World!
messages.bye=bye

使用这段代码:

import configobj
properties = configobj.ConfigObj(propertyFileName)

但是对于多行值,它会失败。

有什么建议吗?

最佳答案

根据ConfigObj documentation , configobj 要求您用三引号将多行值括起来:

Values that contain line breaks (multi-line values) can be surrounded by triple quotes. These can also be used if a value contains both types of quotes. List members cannot be surrounded by triple quotes:

如果无法修改属性文件,我建议使用 configparser :

In config parsers, values can span multiple lines as long as they are indented more than the key that holds them. By default parsers also let empty lines to be parts of values.

这是一个概念的快速证明:

#!/usr/bin/env python
# coding: utf-8

from __future__ import print_function

try:
import ConfigParser as configparser
except ImportError:
import configparser

try:
import StringIO
except ImportError:
import io.StringIO as StringIO

test_ini = """
[some_section]
messages.welcome=Hello\
World
messages.bye=bye
"""
config = configparser.ConfigParser()
config.readfp(StringIO.StringIO(test_ini))
print(config.items('some_section'))

输出:

[('messages.welcome', 'Hello World'), ('messages.bye', 'bye')]

关于python - 如何在 python 中读取多行 .properties 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5984603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com