ConfigParser.get返回一个字符串需要将其转换为section

时间:2014-08-19 23:51:59

标签: python string config configparser

我想使用RawConfigParser.get的返回值(' some section',' someoption')作为另一个RawConfigParser.get的部分,但实际上结果是双倍的包裹的字符串。

section = RawConfigParser.get ('somesection', 'someoption')
subsection = RawConfigParser.get (section, 'someotheroption') # INCORRECT RawConfigParser.get ('"somesection"', 'someotheroption')

我该如何避免这种情况?

2 个答案:

答案 0 :(得分:2)

您有几个选项,其中一个选项是使用ast

>>> quoted_string = '"this is a quote"'
>>> quoted_string
'"this is a quote"'
>>> import ast
>>> unquoted_string = ast.literal_eval(quoted_string)
>>> unquoted_string
'this is a quote'

答案 1 :(得分:0)

您应该实现文件对象并使用RawConfigParser.readfp()

>>> help(ConfigParser.RawConfigParser.readfp)

Help on method readfp in module ConfigParser:

readfp(self, fp, filename=None) unbound ConfigParser.RawConfigParser method
    Like read() but the argument must be a file-like object.

    The `fp' argument must have a `readline' method.  Optional
    second argument is the `filename', which if not given, is
    taken from fp.name.  If fp has no `name' attribute, `<???>' is
    used.