Python escape delimiter in configuration file using ConfigParser

梦想的初衷 提交于 2019-12-20 01:05:57

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/25200269/python-escape-delimiter-in-configuration-file-using-configparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!