Parsing configure file with same section name in python

后端 未结 4 1129
囚心锁ツ
囚心锁ツ 2020-12-30 06:44

I try to parse file like:

[account]
User = first

[account]
User = second

I use ConfigParser in Python, but when i read file:



        
4条回答
  •  清酒与你
    2020-12-30 06:57

    " If you're deviating from an RFC standard and creating your own config format, you're going to have to write your own parser." This http://www.tek-tips.com/viewthread.cfm?qid=1110829 worked for me. I made a couple of small changes. ** formatting did not come out correctly when posted

    def configToDict(file):
    # open the file
    file = open('settings.cfg')
    
    # create an empty dict
    sections = {}
    
    for line in file.readlines():
        # get rid of the newline
        line = line[:-1]
        try:
            # this will break if you have whitespace on the "blank" lines
            if line:
                # skip comment lines
                if line[0] == '#': next
                # this assumes everything starts on the first column
                if line[0] == '[':
                    # strip the brackets
                    section = line[1:-1]
                    # create a new section if it doesn't already exist
                    if not sections.has_key(section):
                        sections[section] = {}
                else:
                    # split on first the equal sign
                    (key, val) = line.split('=', 1)
                    # create the attribute as a list if it doesn't
                    # exist under the current section, this will
                    # break if there's no section set yet
                    if not sections[section].has_key(key):
                        sections[section][key] = []
                    # append the new value to the list
                    sections[section][key].append(val)
        except Exception as e:
            print str(e) + "line:" +line
    return sections
    

提交回复
热议问题