[英]Python - Parse INI text (not INI file)
I have a case where I get a string version of an INI file and not the file itself. 我遇到的情况是我得到的是INI文件的字符串版本,而不是文件本身。 I am getting it this way from an external source and hence cannot be changed.
我是从外部来源以这种方式获取的,因此无法更改。
Example of the string version: 字符串版本的示例:
'[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'
I tried parsing this string using the configParser library in python: 我尝试使用python中的configParser库解析此字符串:
>>> config = configparser.ConfigParser()
>>> config.read(my_ini_str)
[]
I get back nothing with the read function. 我的读取功能一无所获。 Is there any other way to achieve this?
还有其他方法可以做到这一点吗?
Thanks in advance! 提前致谢!
UPDATE - Forgot to add that I am using Python 2. 更新-忘记添加我正在使用Python 2。
This is what the read_string()
method is for. 这就是
read_string()
方法的作用。
Parse configuration data from a string.
从字符串中解析配置数据。
Hence: 因此:
>>> config = configparser.ConfigParser()
>>> config.read_string(my_ini_str)
you have to use read_string
in order to parse a string. 您必须使用
read_string
才能解析字符串。
then you have to use getters on "config" object, such as : 那么您必须在“ config”对象上使用吸气剂,例如:
>>> config.get('dev', 'Host')
'abc.com'
or 要么
>>> config.getfloat(config.default_section, 'Score')
0.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.