开发者

Cannot read sections of config files containing []

开发者 https://www.devze.com 2023-01-11 02:47 出处:网络
Edited post I\'m not able to read the configuration file sections that contain []... for e.g if any section in ini fil开发者_开发知识库e is something like [c:\\\\temp\\\\foo[1].txt] than my script fai

Edited post

I'm not able to read the configuration file sections that contain []... for e.g if any section in ini fil开发者_开发知识库e is something like [c:\\temp\\foo[1].txt] than my script fails to read that section..

config.read(dst_bkp)
for i in config.sections():
    config.get(i,'FileName') 

Thanks, Vignesh


Assuming that you use a builtin subclass of ConfigParser.RawConfigParser module: This is not supported. Even in the newest revision, the regex for section headers is just

SECTCRE = re.compile(
    r'\['                                 # [
    r'(?P<header>[^]]+)'                  # very permissive!
    r'\]'                                 # ]
    )

There is no escaping mechanism, and the section header simply ends at the first closing brackets. You should only use simple strings without "special characters" as header names, not arbitrary strings like file names.

EDIT: Concerning Python 3, the equivalent code has been reorganized a bit, but the regex is the same:

_SECT_TMPL = r"""
    \[                                 # [
    (?P<header>[^]]+)                  # very permissive!
    \]                                 # ]
    """

EDIT 2: You can make your own subclass, as suggested in the other solution, or patch RawConfigParser directly:

import ConfigParser
import re
ConfigParser.RawConfigParser.SECTCRE = re.compile(r"\[(?P<header>.+)\]")

However, I'd suggest not doing any of these and avoid the brackets instead. If you have brackets in section headers, your configuration files are likely to be unportable.


That happens because of the regexp used to parse the header -- it goes only as far as the first closing bracket.

You can fix it for your program by subclassing ConfigParser.ConfigParser:

import ConfigParser
import re

class MyConfigParser(ConfigParser.ConfigParser):
    SECTCRE = re.compile(
        r'\['                                 # [
        r'(?P<header>.+)'                     # even more permissive!
        r'\]'                                 # ]
        )

config = MyConfigParser()
config.read(dst_bkp)
for i in config.sections():
    config.get(i,'FileName') 
0

精彩评论

暂无评论...
验证码 换一张
取 消