Configparser and string with %

Question:

Stupid question with (for sure) simple answer…

I am using configparser to read some strings from a file. When the string has the ‘%’ symbol ($%& for example) it complains:

ConfigParser.InterpolationSyntaxError: ‘%’ must be followed by ‘%’ or ‘(‘, found: “%&'”

Anybody familiar with this?

Thanks!

Asked By: Hüsk3rDü

||

Answers:

If you don’t want environment variable substitution, then use RawConfigParser, not ConfigParser.

Answered By: Ned Batchelder

Write two %:

V = ('%%', 'MHz', 'GHz')

result:

('%', 'MHz', 'GHz')
Answered By: Artem Baranov

By default, ConfigParser has interpolation of values enabled. That means that you can use variables inside your properties files.

Since Python 3.2, you can disable interpolation in the constructor:

configParser = configparser.ConfigParser(interpolation=None)

If you don’t want to disable interpolation, you must escape the % sign by putting two consecutive %% in the properties file as shown in the example of the documentation.

Note that RawConfigParser is a legacy variant. From the python documentation:

Consider using ConfigParser instead which checks types of the values
to be stored internally. If you don’t want interpolation, you can use
ConfigParser(interpolation=None).

Answered By: Christophe Weis
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.