striok
striok

Reputation: 21

Python configparser special character

I try using configparser module but I have a little problem with it.

This is a example of code:

import configparser

ini_file = """[s1]\nl1 = 01\n= = 02\n[s2]\n l2 = 123"""
print (ini_file)

config = configparser.ConfigParser()
config.read_string(ini_file)
config.sections()

Can I use a spacial character in keys like = or : ?

(example = = 02 where first = is key and 02 is value)

(In ANSI-C I can use \" to print " - special char). Maybe in python it's similar :)

Thanks for answer!

Upvotes: 2

Views: 5739

Answers (2)

oraclesoon
oraclesoon

Reputation: 803

I am using Python version 3.11.4.

By specifying raw=True when reading the ini file, it can read special characters as they are.

This is the sample config.ini

[TEST]
special="""[s1]\nl1 = 01\n= = 02\n[s2]\n l2 = 123"""

The following is the Python script:

import configparser

config = configparser.ConfigParser()
config.read("config.ini")

special = config.get('TEST', 'special', raw=True)
print(special)

Output:

"""[s1]\nl1 = 01\n= = 02\n[s2]\n l2 = 123"""

Upvotes: 0

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19144

No and yes.

No: Python uses '\' to escape special characters in strings, but not in code. The re module also uses '\' to escape characters that are special in re strings. Configparser does not use '\' or any other escape character.

Yes: The '=' and ':' are the default separators between key and values, but only the defaults. They can be changed (for an entire file) with a delimiters keyword argument in a Configparser(delimiters=<something else>) call. From configparser doc:

delimiters, default value: ('=', ':')

Delimiters are substrings that delimit keys from values within a section. The first occurrence of a delimiting substring on a line is considered a delimiter. This means values (but not keys) can contain the delimiters.

Upvotes: 3

Related Questions