【问题标题】:Python - Parse INI text (not INI file)Python - 解析 INI 文本(不是 INI 文件)
【发布时间】:2019-03-09 05:28:28
【问题描述】:

我有一个案例,我得到的是 INI 文件的字符串版本,而不是文件本身。我是从外部来源以这种方式获取的,因此无法更改。

字符串版本示例:

'[DEFAULT]\nScore = 0.1\n\n[dev]\nHost = abc.com\nPort = 0000\n\n[qa]\nHost = xyz.com\nEsPort = 1000\n\n[main]\nHost = pqr.com\nPort = 2000\n'

我尝试使用 python 中的 configParser 库来解析这个字符串:

>>> config = configparser.ConfigParser()
>>> config.read(my_ini_str)
[]

读取功能我什么也得不到。有没有其他方法可以做到这一点?

提前致谢!

更新 - 忘了补充说我使用的是 Python 2。

【问题讨论】:

标签: python string ini configparser


【解决方案1】:

这就是read_string() 方法的用途。

从字符串中解析配置数据。

因此:

>>> config = configparser.ConfigParser()
>>> config.read_string(my_ini_str)

【讨论】:

  • 我试过这个,但得到了这个错误: Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.7/site-packages /backports/configparser/__init__.py", line 728, in read_string sfile = io.StringIO(string) TypeError: initial_value must be unicode or None, not str
  • 似乎该函数存在于 Python 3 中,但不存在于 Python 2 中。
  • @activelearner:根据该错误消息,您需要先将字符串解码为unicode
【解决方案2】:

您必须使用read_string 才能解析字符串。

那么你必须在“config”对象上使用getter,例如:

>>> config.get('dev', 'Host')
'abc.com'

>>> config.getfloat(config.default_section, 'Score')
0.1

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2015-10-12
    • 2021-01-06
    • 2018-08-30
    • 2012-09-24
    • 2010-09-29
    相关资源
    最近更新 更多