user2994682
user2994682

Reputation: 503

ConfigParser.get returning a string need to convert it to section

I want to use the return value of RawConfigParser.get ('somesection', 'someoption') as the section for another RawConfigParser.get, but in practice the result is a doubly encased string.

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

How do I avoid this?

Upvotes: 0

Views: 2409

Answers (2)

LittleQ
LittleQ

Reputation: 1925

You should realized a file-object and use 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.

Upvotes: 0

C.B.
C.B.

Reputation: 8326

You have a couple options, one of which is to use the ast library

>>> 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'

Upvotes: 2

Related Questions