简体   繁体   中英

Python escape delimiter in configuration file using ConfigParser

I'd like to escape ":" and/or "=" as the name in a configuration file. Does anyone know how to achieve this? I try backslash "\\", it does not work.

If you're using Python 3, you don't need to. Look at the Python docs section on Customizing Parser Behavior . By default, configparser uses ":" and "=" as delimiters, but you can specify different delimiters when you create the configparser object:

import configparser

parser = configparser.ConfigParser(delimiters=('?', '*'))

In this example, the default delimiters have been replaced with a question mark and an asterisk. You can change the delimiters to whatever characters you want that won't conflict with the information you need to put in the config file.

The above listed method will only work for Python 3, as the Python 2 ConfigParser is hard-coded to recognize equal signs and colons as delimiters. According to this SO question , there is a backported configparser available for the 2.7 intepreter at https://pypi.python.org/pypi/configparser . See if that will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM